Created
June 22, 2010 13:21
-
-
Save forki/448453 to your computer and use it in GitHub Desktop.
Sample for using the maybe monad 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
public static class MaybeConcat | |
{ | |
public static Maybe<T> Concat<T>(this Maybe<T> source1, Func<Maybe<T>> source2F) | |
{ | |
return source1.IsNone ? source2F() : source1; | |
} | |
} | |
public class HaskellLookupSample | |
{ | |
private static readonly Dictionary<string, string> FullNamesDb = | |
new Dictionary<string, string> | |
{ | |
{ "Bill Gates", "billg@microsoft.com" }, | |
{ "Bill Clinton", "bill@hope.ar.us" }, | |
{ "Michael Jackson", "mj@wonderland.org" } | |
}; | |
private static readonly Dictionary<string, string> NickNamesDb = | |
new Dictionary<string, string> | |
{ | |
{ "billy", "billg@microsoft.com" }, | |
{ "slick willy", "bill@hope.ar.us" }, | |
{ "jacko", "mj@wonderland.org" } | |
}; | |
private static readonly Dictionary<string, string> PrefsDb = | |
new Dictionary<string, string> | |
{ | |
{ "billg@microsoft.com", "HTML" }, | |
{ "bill@hope.ar.us", "Plain" }, | |
{ "mj@wonderland.org", "HTML" } | |
}; | |
[Fact] | |
public void DictionaryLookup() | |
{ | |
Assert.Equal("HTML", LookUp("billy").Some); | |
Assert.Equal("HTML", LookUp("Bill Gates").Some); | |
Assert.True(LookUp("Steffen").IsNone); | |
} | |
private static Maybe<string> LookUp(string text) | |
{ | |
return | |
FullNamesDb.TryFind(text) | |
.Concat(() => NickNamesDb.TryFind(text)) // Lazy | |
.SelectMany(y => PrefsDb.TryFind(y)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment