Skip to content

Instantly share code, notes, and snippets.

@jdoiwork
Last active June 5, 2020 09:55
Show Gist options
  • Save jdoiwork/c0518a13d25a64c597b8b45a93bcbd11 to your computer and use it in GitHub Desktop.
Save jdoiwork/c0518a13d25a64c597b8b45a93bcbd11 to your computer and use it in GitHub Desktop.
C# Maybe Monad as Linq
using System;
using System.Collections.Generic;
using System.Linq;
public abstract class Maybe<T> {
public Maybe<TResult> Map<TResult>(Func<T, TResult> selector)
{
return this.Bind(a => new Just<TResult>(selector(a)));
}
public Maybe<TResult> Select<TResult>(Func<T, TResult> selector)
{
return this.Map(selector);
}
public abstract Maybe<TResult> Bind<TResult>(Func<T, Maybe<TResult>> tempSelector);
public Maybe<TResult> SelectMany<TTemp, TResult>(Func<T, Maybe<TTemp>> tempSelector, Func<T, TTemp, TResult> resultSelector)
{
return this.Bind(a => tempSelector(a).Map(b => resultSelector(a, b)));
}
}
public class Nothing<T> : Maybe<T> {
public override string ToString()
{
return "Nothing";
}
public override Maybe<TResult> Bind<TResult>(Func<T, Maybe<TResult>> tempSelector)
{
return new Nothing<TResult>();
}
}
public class Just<T> : Maybe<T> {
public Just(T t) {
this.Value = t;
}
public T Value { set; get;}
public override string ToString()
{
return $"Just {this.Value}";
}
public override Maybe<TResult> Bind<TResult>(Func<T, Maybe<TResult>> tempSelector)
{
return tempSelector(this.Value);
}
}
public class Hello{
public static void Main(){
// Your code here!
var query1 =
from x in new Just<int>(1)
from y in new Just<int>(2)
select x + y;
var query2 =
from x in new Just<int>(1)
from y in new Nothing<int>()
select x + y;
var query3 =
from x in new Nothing<int>()
from y in new Just<int>(2)
select x + y;
var query4 =
from x in new Nothing<int>()
from y in new Nothing<int>()
select x + y;
var query5 =
from x in new Just<int>(1)
from y in new Just<int>(2)
from z in new Just<int>(3)
select x + y + z;
var query6 =
from x in new Just<int>(1)
from y in new Nothing<int>()
from z in new Just<int>(3)
select x + y + z;
var qs = new List<Maybe<int>>{
query1,
query2,
query3,
query4,
query5,
query6,
};
qs.ForEach(System.Console.WriteLine);
}
}
@jdoiwork
Copy link
Author

jdoiwork commented Jun 4, 2020

TODO: Select, SelectMany as Extension Methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment