Skip to content

Instantly share code, notes, and snippets.

@yurug
Created June 13, 2019 14:48
Show Gist options
  • Save yurug/0d0ab0682a11a91a0648b47c036df8ea to your computer and use it in GitHub Desktop.
Save yurug/0d0ab0682a11a91a0648b47c036df8ea to your computer and use it in GitHub Desktop.
The ErrorMonad in OCaml
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