Last active
December 18, 2018 20:08
-
-
Save thealmarty/2d4d5bb23c279b71c3c99c769007d29e to your computer and use it in GitHub Desktop.
Iterate function using unfold in OCaml
This file contains 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
(* The unfold function takes in | |
a predicate (p) and | |
a function (g) which takes an input (b). *) | |
let rec unfold p g b = | |
if p b then [] else | |
(match g b with (a, bprime) -> | |
a :: unfold p g bprime) | |
;; | |
(* The iterate function takes in a function (f), | |
and uses the unfold function with p and g passed. | |
b is to be passed. *) | |
(* This function is equivalent to the Haskell iterate function. *) | |
let iterate f = unfold (fun x -> false) (fun x -> (x, (f x)));; | |
(* Giving unfold a predicate of x > 20 returns a list. *) | |
let iterate_p f = unfold (fun x -> (x > 20)) (fun x -> (x, (f x)));; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See the blog post.