Skip to content

Instantly share code, notes, and snippets.

@bruno-cadorette
Created April 27, 2016 09:37
Show Gist options
  • Select an option

  • Save bruno-cadorette/e574fbaf0b80a01e6ace61e4b1c8bd87 to your computer and use it in GitHub Desktop.

Select an option

Save bruno-cadorette/e574fbaf0b80a01e6ace61e4b1c8bd87 to your computer and use it in GitHub Desktop.
Haskell like maybe in C#. Contains functor, applicative functor and monad implementation. Do not use this in real code, C# 6.0 have the ?. operator that is nearly the same thing
using System;
namespace MaybeCSharp
{
interface IMaybe<T>
{
IMaybe<U> Bind<U>(Func<T, IMaybe<U>> f);
IMaybe<U> Map<U>(Func<T, U> f);
IMaybe<U> Ap<U>(IMaybe<Func<T, U>> f);
}
class Just<T> : IMaybe<T>
{
private T _Value;
private Just(T value)
{
_Value = value;
}
public static IMaybe<T> Pure(T val)
{
return new Just<T>(val);
}
public IMaybe<U> Ap<U>(IMaybe<Func<T, U>> app)
{
return app.Bind(f => Just<U>.Pure(f(_Value)));
}
public IMaybe<U> Bind<U>(Func<T, IMaybe<U>> f)
{
return f(_Value);
}
public IMaybe<U> Map<U>(Func<T, U> f)
{
return new Just<U>(f(_Value));
}
public override string ToString()
{
return $"Some {_Value}";
}
}
class Nothing<T> : IMaybe<T>
{
public static IMaybe<T> None = new Nothing<T>();
public IMaybe<U> Ap<U>(IMaybe<Func<T, U>> f)
{
return new Nothing<U>();
}
public IMaybe<U> Bind<U>(Func<T, IMaybe<U>> f)
{
return new Nothing<U>();
}
public IMaybe<U> Map<U>(Func<T, U> f)
{
return new Nothing<U>();
}
public override string ToString()
{
return "Nothing";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment