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:
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() = | |
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 |
Comments