All pastes #980524 Raw Edit

Something

public text v1 · immutable
·published 2008-04-11 01:57 UTC
rendered paste body
// Main.cs, an example of usage

using System;
using Parser;

...
	static void Main()
	{
	    Parsed<int> x = new Ok<int>(4);

	    // Is there any way to avoid having to write "Parsed<int>.Fn<int>"?
	    // I'm trying to use some pattern-matching-esque idiom.

	    Console.WriteLine(x.Match(new Parsed<int>.Fn<int> {
		Ok = z => z.Value,
		Error = z => 9
	    }));

	}


// Result.cs:

using System;

namespace Parser {

    public abstract class Parsed<A> {
	// A Parsed<A>.Fn<T>, as used by Match, performs an action depending on the type.
	public class Fn<T> {
	    public Func<Ok<A>, T> Ok { get; set; }
	    public Func<Error<A>, T> Error { get; set; }
	}

	public List<string> Context { get; private set; }

	// You can see that Match<T> takes a Fn<T> and in the children
	// calls the right method.
	abstract public T Match<T>(Fn<T> matcher);
    }

    public class Ok<A> : Parsed<A> {
	public A Value { get; private set; }

	public override T Match<T>(Fn<T> matcher) {
	    return matcher.Ok(this);
	}

	public Ok(A value) {
	    this.Value = value;
	}
    }

    public class Error<A> : Parsed<A> {

	public string Message { get; private set; }

	public Error(string message)
	    : this(message, new List<string>())
	{
	}

	public Error(string message, List<string> context) {
	    Message = message;
	    Context = context;

	}

	public override T Match<T>(Fn<T> matcher) {
	    return matcher.Error(this);
	}

    }

}