Maybe monad in F#

F# supports writing custom monads very well. Take a look at (famous :) maybe monad which is just 6 lines of code:

type Maybe() =
member __.Bind(value, rest) =
if value = null then null else rest value
member __.Return(value) =
value
let maybe = new Maybe()
let substring (str: string) (from: int) =
maybe {
let! x = str
let! substr = x.Substring from
return "[" + substr + "]"
}
// test it with not null string
> substring "1234" 2;;
> val it : string = "[34]"
// and now with null string
> substring null 2;;
> val it : string = null
view raw gistfile1.fs hosted with ❤ by GitHub

Comments

Popular posts from this blog

Regular expressions: Rust vs F# vs Scala

Hash maps: Rust, F#, D, Go, Scala

Haskell: performance