Last active
January 24, 2019 23:00
-
-
Save thealmarty/6d86b9bbacdc82a2874de9624f6a10c6 to your computer and use it in GitHub Desktop.
The factorial function using hylomorphism 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
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