Created
June 13, 2019 14:48
-
-
Save yurug/0d0ab0682a11a91a0648b47c036df8ea to your computer and use it in GitHub Desktop.
The ErrorMonad in OCaml
This file contains hidden or 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
module ErrorMonad : sig | |
type 'a t | |
val ret : 'a -> 'a t | |
val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t | |
val fail : 'a t | |
val run : 'a t -> 'a option | |
end = struct | |
type 'a t = 'a option | |
let ret x = Some x | |
let fail = None | |
let run x = x | |
let ( >>= ) x f = match x with None -> None | Some x -> f x | |
end | |
let some_monadic_code x = ErrorMonad.(run ( | |
if x = 0 then fail else ret (x + 1) >>= fun y -> | |
if y mod 3 = 1 then fail else ret (y * 2) >>= fun z -> | |
ret z | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment