Skip to content

Instantly share code, notes, and snippets.

@thealmarty
Last active January 24, 2019 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thealmarty/6d86b9bbacdc82a2874de9624f6a10c6 to your computer and use it in GitHub Desktop.
Save thealmarty/6d86b9bbacdc82a2874de9624f6a10c6 to your computer and use it in GitHub Desktop.
The factorial function using hylomorphism in OCaml.
let rec unfold p g b =
if p b then [] else
(match g b with (a, bprime) ->
a :: unfold p g bprime)
let fact n =
List.fold_right
(* The fold's function input is the times function.*)
(fun x y -> x * y)
(* The fold's list input is the result of this unfold. *)
(unfold
(* The unfold function's predicate to stop is n=0. *)
(fun n -> (n = 0))
(* The unfold's g n = (n, n-1) *)
(fun n -> (n, (n - 1)))
(* The unfold's input is n, the input to the fact function. *)
n)
(* The fold's base case is one. *)
1
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment