Skip to content

Instantly share code, notes, and snippets.

@vmarquez
Created December 1, 2013 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vmarquez/7740602 to your computer and use it in GitHub Desktop.
Save vmarquez/7740602 to your computer and use it in GitHub Desktop.
Writer Monad in C#
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