Skip to content

Instantly share code, notes, and snippets.

@mcapodici
Created July 26, 2015 21:00
Show Gist options
  • Save mcapodici/8335ebbba55ed3130d25 to your computer and use it in GitHub Desktop.
Save mcapodici/8335ebbba55ed3130d25 to your computer and use it in GitHub Desktop.
List Monad implemented in C#
using System;
using System.Collections.Generic;
using System.Linq;
namespace Monad
{
class Program
{
static void Main(string[] args)
{
// Equivalent to: fmap show [1..3]
var result1 = FMap(Enumerable.Range(1,3), x => x.ToString());
// Equivalent to: (+) <$> [1,2,3] <*> [1,2,3]
var result2 =
Apply(Enumerable.Range(1, 3),
FMap<int, Func<int,int>>(Enumerable.Range(1, 3), x => (y => x + y)));
// Equivalent to: [1..3] >>= (\x -> [1..3] >>= (\y -> return (x,y)))
// or: do; x <- [1..3]; y <- [1..3]; return (x,y)
// or: [(x,y) | x <- [1..3], y <- [1..3]]
var result3 =
Bind(Enumerable.Range(1,3), x =>
Bind(Enumerable.Range(1,3), y =>
Pure(Tuple.Create(x,y))));
}
static IEnumerable<T> Pure<T>(T val)
{
yield return val;
}
static IEnumerable<U> Bind<T,U>(IEnumerable<T> mt, Func<T, IEnumerable<U>> f_t_mu)
{
return mt.SelectMany(f_t_mu);
}
static IEnumerable<U> Apply<T,U>(IEnumerable<T> mt, IEnumerable<Func<T,U>> m_f_t_u)
{
return Bind(mt, t => Bind(m_f_t_u, f => Pure(f(t))));
}
static IEnumerable<U> FMap<T, U>(IEnumerable<T> mt, Func<T,U> f_t_u)
{
return Apply(mt, Pure(f_t_u));
}
}
}
@mcapodici
Copy link
Author

List Monad implemented in C# (pure, bind).
Apply and FMap derived in 'generic' way using only pure/bind and without directly using the IEnumerable interface.

@gsscoder
Copy link

👍

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