Seq.unfold is a function hard-to-understand if I read any Microsoft's documents and any books. For example, the way in "Programming F# 3.0, 2nd Edition" is hard to understand.
> // Generate the next element of the Fibonacci sequence given the previous
// two elements. To be used with Seq.unfold.
let nextFibUnder100 (a, b) =
if a + b > 100 then
None
else
let nextValue = a + b
Some(nextValue, (nextValue, a));;
val nextFibUnder100 : int * int -> (int * (int * int)) option
> let fibsUnder100 = Seq.unfold nextFibUnder100 (0, 1);;
val fibsUnder100 : seq<int>
> Seq.toList fibsUnder100;;
val it : int list = [1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89]
But, since I re-write this example verbosely like below, I can understand about it.
module UnfoldVerbosely =
let fibSeed (current, next) =
let yieldValue = current
let next'current = next
let next'next = current + next
Some(yieldValue, (next'current, next'next))
let fib = Seq.unfold fibSeed (1L, 1L)
printfn "%A" (Seq.take 2 UnfoldVerbosely.fib)
printfn "%A" (Seq.take 3 UnfoldVerbosely.fib)
printfn "%A" (Seq.take 4 UnfoldVerbosely.fib)
printfn "%A" (Seq.take 5 UnfoldVerbosely.fib)
module UnfoldVerbosely = begin val fibSeed : current:int * next:int -> (int * (int * int)) option val fib : seq<int> end seq [1; 1] seq [1; 1; 2] seq [1; 1; 2; 3] seq [1; 1; 2; 3; ...]
No comments:
Post a Comment