Created
December 1, 2013 20:48
-
-
Save vmarquez/7740602 to your computer and use it in GitHub Desktop.
Writer Monad in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace XSharpx { | |
public struct Writer<A, B> | |
{ | |
public readonly A a; | |
public readonly B b; | |
public readonly Semigroup<A> semigroup; | |
public Writer(A a, B b, Semigroup<A> semigroup) | |
{ | |
this.a = a; | |
this.b = b; | |
this.semigroup = semigroup; | |
} | |
public Tuple<A, B> Apply() | |
{ | |
return new Tuple<A, B>(a, b); | |
} | |
} | |
public static class WriterExtensions | |
{ | |
public static Writer<A, C> Select<A, B, C>(this Writer<A, B> w, Func<B, C> f) | |
{ | |
var c = f(w.b); | |
return new Writer<A, C>(w.a, c, w.semigroup); | |
} | |
public static Writer<A, D> SelectMany<A, B, C, D>(this Writer<A, B> w, Func<B, Writer<A,C>> bind, Func<B, C, D> select) | |
{ | |
return SelectMany(w, b => Select(bind(b), c => select(b, c))); | |
} | |
public static Writer<A, C> SelectMany<A, B, C>(this Writer<A, B> w, Func<B, Writer<A, C>> f) | |
{ | |
var wb = f(w.b); | |
var na = w.semigroup.Apply(w.a, wb.a); | |
return new Writer<A, C>(na, wb.b, wb.semigroup); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment