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 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
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", "[email protected]" }, | |
{ "Bill Clinton", "[email protected]" }, | |
{ "Michael Jackson", "[email protected]" } | |
}; | |
private static readonly Dictionary<string, string> NickNamesDb = | |
new Dictionary<string, string> | |
{ | |
{ "billy", "[email protected]" }, | |
{ "slick willy", "[email protected]" }, | |
{ "jacko", "[email protected]" } | |
}; | |
private static readonly Dictionary<string, string> PrefsDb = | |
new Dictionary<string, string> | |
{ | |
{ "[email protected]", "HTML" }, | |
{ "[email protected]", "Plain" }, | |
{ "[email protected]", "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