Skip to content

Instantly share code, notes, and snippets.

@thealmarty
Last active December 18, 2018 20:08
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/2d4d5bb23c279b71c3c99c769007d29e to your computer and use it in GitHub Desktop.
Save thealmarty/2d4d5bb23c279b71c3c99c769007d29e to your computer and use it in GitHub Desktop.
Iterate function using unfold in OCaml
(* 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)));;
@thealmarty
Copy link
Author

See the blog post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment