Last active
December 20, 2015 02:29
-
-
Save leon737/6056653 to your computer and use it in GitHub Desktop.
F# monads
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
Monads implemented: | |
Maybe | |
Reader | |
Writer |
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
type Maybe<'a> = | |
| Just of 'a | |
| Nothing | |
let Return x = Just x | |
let Bind mx f = | |
match mx with | |
| Just x -> f x | |
| Nothing -> Nothing | |
let (>>=) = Bind |
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
type Reader<'v> = Reader of 'v | |
let Return v = Reader v | |
let runReader mx d = | |
match mx with | |
| Reader v -> v d | |
let Bind mx f = | |
match mx with | |
| Reader v -> Reader (fun z -> (v z) |> f |> runReader <| z) | |
let (>>=) = Bind | |
///////////////////////////////////////////////////////////////////////////// | |
let greeter = | |
Return (fun n -> "hello, " + n + "!") | |
let calc (s:string) = | |
Return (fun (n:string) -> s.Length - n.Length) | |
let config = "leon" | |
let r = runReader (greeter >>= calc) config |
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
type Writer<'d, 'v> = Writer of 'd * 'v | |
let Tell d f = f d | |
let Return v = fun d -> Writer(d,v) | |
let Join d mx = | |
match mx with | |
| Writer(x:string,v) -> Writer(d+x, v) | |
let Bind mx f = | |
match mx with | |
| Writer(d,v) -> f v |> Join d | |
let runWriter mx = | |
match mx with | |
| Writer(d,v) -> d,v | |
let (>>=) = Bind | |
///////////////////////////////////////////////////////////////////////////// | |
let half x = | |
Tell ( sprintf "I just halved %d ! " x ) <| Return ( x / 2 ) | |
let log, result = half 8 >>= half |> runWriter | |
printfn "Log: %s" log | |
printfn "Result: %d" result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment