Created
July 26, 2015 21:00
-
-
Save mcapodici/8335ebbba55ed3130d25 to your computer and use it in GitHub Desktop.
List Monad implemented in C#
This file contains 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 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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.