0

I'm relatively new to Ocaml and think I'm understanding the Unfold function correctly but I just can't see how to make a fibonacci sequence using it. Wouldn't we need to have a holder variable of the last two values so we could find the current one? All help is greatly appreciated. I'm adding the Unfold function below for reference.

let rec unfold (f: 'seed -> ('a * 'seed)) (stop : 'b -> bool) (b :'seed) : 'a list =
if stop b then []
else 
  let x, b' = f b in
   x :: (unfold f stop b')
ohhimark
  • 11
  • 5

1 Answers1

2

You had the right idea of storing the last two values to create the next one. The trick is to store them in a tuple.

The generator function takes the tuple, returns the first number as the generated value and creates a new state with the second number of the tuple and the next fibonacci number:

fun (a, b) -> (a, (b, a+b))

The stop function just takes the tuple and decides when to stop, e.g.

fun (a, b) -> a > 1000

The first state is (0, 1) which are the first two fibonacci numbers.

Putting it all together:

# unfold (fun (a, b) -> (a, (b, a+b))) (fun (a, b) -> a > 1000) (0, 1);;
- : int list =
[0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; 610; 987]
Palle
  • 11,511
  • 2
  • 40
  • 61