Created
October 3, 2011 00:36
-
-
Save hodzanassredin/1258177 to your computer and use it in GitHub Desktop.
linq monad
This file contains hidden or 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; | |
| using System.Text; | |
| using System.IO; | |
| using Monad; | |
| using System.Collections; | |
| namespace Monad | |
| { | |
| public class Maybe<T> | |
| { | |
| public readonly static Maybe<T> Nothing = new Maybe<T>(); | |
| public T Value { get; private set; } | |
| public bool HasValue { get; private set; } | |
| Maybe() | |
| { | |
| HasValue = false; | |
| } | |
| public Maybe(T value) | |
| { | |
| Value = value; | |
| HasValue = true; | |
| } | |
| } | |
| public static class Helpers//monad in linq | |
| { | |
| public static Maybe<T> ToMaybe<T>(this T value) | |
| { | |
| return new Maybe<T>(value); | |
| } | |
| public static Maybe<U> SelectMany<T, U>(this Maybe<T> m, Func<T, Maybe<U>> k) //bind | |
| { | |
| if (!m.HasValue) | |
| return Maybe<U>.Nothing; | |
| return k(m.Value); | |
| } | |
| public static Maybe<V> SelectMany<T, U, V>( | |
| this Maybe<T> id, | |
| Func<T, Maybe<U>> k, | |
| Func<T, U, V> s) | |
| { | |
| return id.SelectMany(x => k(x).SelectMany(y => s(x, y).ToMaybe())); | |
| } | |
| } | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| //list monad | |
| var result2 = from x in new List<int> { 1, 2, 3 } | |
| from y in new List<int> { 4, 5, 6 } | |
| select Tuple.Create(x,y); | |
| //maybe monad | |
| var r = from x in 5.ToMaybe() | |
| from y in Maybe<int>.Nothing | |
| select x + y; | |
| Console.WriteLine(r.HasValue ? r.Value.ToString() : "Nothing"); | |
| Console.ReadLine(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment