Skip to content

Instantly share code, notes, and snippets.

@cowlike
Last active September 1, 2019 15:05
Show Gist options
  • Save cowlike/53144912970de8f01a7906b076f34b5b to your computer and use it in GitHub Desktop.
Save cowlike/53144912970de8f01a7906b076f34b5b to your computer and use it in GitHub Desktop.
Monad transformer example using FSharpPlus
#r "/Users/cowlike/.nuget/packages/fsharpplus/1.1.0-ci00271/lib/netstandard2.0/FSharpPlus.dll"
open FSharpPlus
open FSharpPlus.Data
let doAsyncThing = async {return System.DateTime.Now}
let doNextAsyncThing (x:System.DateTime) = async {
let m = x.Millisecond
return (if m < 500 then Some m else None)
}
let f x = 2 * x
let run1 = monad {
let! x = lift doAsyncThing
let! y = OptionT (doNextAsyncThing x)
return f y
}
let doResultThing: Result<System.Random,string> = Ok <| System.Random()
let doNextResultThing (rand: System.Random): Result<int option,string> = monad {
let r = rand.Next(10)
return (if r < 5 then Some r else None)
}
let run2 = monad {
let! x = lift doResultThing
let! y = OptionT (doNextResultThing(x))
return f y
}
let run3 = monad {
let realInt: Result<int option,string> = return (Some 1)
let! x = OptionT realInt
return x * 10 }
OptionT.run run3 |> printfn "%A"
run3 >>= (fun p -> lift (return (p * 10)))
|> OptionT.run
|> printfn "%A"
|> ignore
let run4 = monad {
let realInt: Option<Result<int,string>> = Some (result 1)
let! x = ResultT realInt
return x * 10 }
run4 >>= (fun p -> lift (Some (p * 10)))
|> ResultT.run
|> printfn "%A"
|> ignore
@cowlike
Copy link
Author

cowlike commented Aug 31, 2019

Example using FSharpPlus, slightly extended example from this StackOverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment