calebh
9/27/2018 - 9:04 PM

Monad C# example

Monad C# example

typeclassinstance Monad<Nullable> {
    Nullable<b> >>=<a,b>(Nullable<a> val, Func<a, Nullable<b>> f) {
        if (val.HasValue) {
            return f(val.Value);
        } else {
            return null;
        }
    }

    Nullable<a> return_<a>(a val) {
        return new Nullable<a>(val);
    }

    Nullable<b> >><a,b>(Nullable<a> wrappedA, Nullable<b> wrappedB) {
        return >>=(wrappedA, (a unwrappedA) => wrappedB);
    }
}

typeclassinstance Monad<List> {
    List<b> >>=<a,b>(List<a> lst, Func<a, List<b>> f) {
        List<b> output = new List<b>();
        foreach (a val in lst) {
            // f(val) will return a list, so we concatenate the result
            // of f(val) onto the end of the output list
            output.AddRange(f(val));
        }

        return output;
    }

    List<a> return_<a>(a val) {
        return new List<b>() { val };
    }

    List<b> >><a,b>(List<a> wrappedA, List<b> wrappedB) {
        return >>=(wrappedA, (a unwrappedA) => wrappedB);
    }
}