Adrian
Adrian

Reputation: 1036

F# generator function equivalent

In JavaScript, ES6 flavor, was introduced generator function so this kind of constructs are possible:

var fib = function *(max) {
  var x = 0, y = 1, tmp = 1;
  while (tmp<max) {
    yield tmp;
    x = y; 
    y = tmp;
    tmp = x + y;
  }
}
var fibgen = fib(3000);

Here fibgen is a generator that will produce lower than 3000 Fibonacci numbers.

What would be an equivalent construct in F#?

LE: I'm not looking for an algorithm for Fibonacci series. But for some generator function that would lazily emit a value when iterating over it.

Upvotes: 2

Views: 1165

Answers (1)

Vandroiy
Vandroiy

Reputation: 6223

See this MSDN article for lazily evaluated sequences in F#. A possible solution to the given problem, using Seq.unfold:

let fibTo limit =
    Seq.unfold (fun (a, b) -> Some (b, (b, a+b))) (0I, 1I)
    |> Seq.takeWhile (fun i -> i <= limit)

The first line creates the Fibonacci sequence, lazily evaluated. The second limits it. I is the literal for arbitrary-length integers. Test:

fibTo 3000I |> Seq.iter (printf "%A ")

Output: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584

fibTo (pown 10I 30)

Returns the Fibonnaci sequence up to 898923707008479989274290850145 – the last value no larger than 10^30 – if evaluated that far.

Upvotes: 6

Related Questions