Skip to content

Instantly share code, notes, and snippets.

@cwfoo
Created September 22, 2021 03:15
Show Gist options
  • Select an option

  • Save cwfoo/ae1a830b3c288ecea1a7fd192e2c9fae to your computer and use it in GitHub Desktop.

Select an option

Save cwfoo/ae1a830b3c288ecea1a7fd192e2c9fae to your computer and use it in GitHub Desktop.
"Maybe" monad in OCaml
(* "Maybe" monad in OCaml.
* References:
* * https://www.cs.cornell.edu/courses/cs3110/2019sp/textbook/ads/monads.html
* * https://www.cs.cornell.edu/courses/cs3110/2019sp/textbook/ads/ex_maybe_monad.html
*)
module type Monad =
sig
type 'a t
val return : 'a -> 'a t
(* Bind. *)
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
end
module Maybe : (Monad with type 'a t = 'a option) =
struct
type 'a t = 'a option
let return x = Some x
let (>>=) x f =
match x with
| None -> None
| Some a -> f a
end
(* Helper function. *)
let string_of_option = function
| None -> "None"
| Some x -> "Some " ^ (string_of_int x)
let divide (x:int) (y:int) : int option =
match y with
| 0 -> None (* Division by zero. *)
| _ -> Some (x / y)
(* Calculate (((16 / 2) / 2) / 2) + 1 *)
open Maybe
let () =
let solution =
Some 16 >>= fun w ->
divide w 2 >>= fun x ->
divide x 2 >>= fun y ->
divide y 2 >>= fun z ->
return (z + 1) in
print_endline (string_of_option solution)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment