Created
June 4, 2018 16:12
-
-
Save manio143/8ff93ddbbe746bf4a2f9b49640a61041 to your computer and use it in GitHub Desktop.
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
// F#+ sample monad usage | |
#r "FSharpPlus.dll" | |
open FSharpPlus | |
open FSharpPlus.Data | |
//open FSharpPlus.Operators | |
let s9 = Some 9 | |
let add5divXmul2 (o : int option) x = monad { | |
let! a = o | |
let aa = a + 5 | |
let div a b = if b = 0 then None else result (a/b) | |
let b = div aa x | |
let! c = map (fun x -> x * 2) b | |
return c | |
} | |
let sum (l: int list) : Writer<int, unit> = monad { | |
for x in l do | |
do! tell x | |
} | |
let inline (>>-) a b = a >>= fun _ -> b | |
let addMS (x:int) : StateT<int, 'a> = monad { | |
let! a = get | |
return a + x | |
} | |
let stateRes : StateT<int, Result<int * int, string>> = | |
let r1 : StateT<int, Result<int * int, string>> = monad {return 1} | |
r1 >>= put >>- addMS 2 | |
let butWithError : StateT<int, Result<int * int, string>> = stateRes >>- lift (Error "err") | |
printfn "TEST 1: add5divXmul2 s9 7 = %A" <| add5divXmul2 s9 7 | |
printfn "TEST 2: add5divXmul2 s9 0 = %A" <| add5divXmul2 s9 0 | |
printfn "TEST 3: sum [1..10] = %A" <| sum [1..10] | |
printfn "TEST 4: StateT.run stateRes 0 = %A" <| StateT.run stateRes 0 | |
printfn "TEST 4: StateT.run butWithError 0 = %A" <| StateT.run butWithError 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment