I'm learning about F#, and there are 2 ways of generating sequences that i came across so far, and i'm curious about the differences between them if any.
First way:
Seq.unfold(fun x -> Some(x, x + 1)) 1 |> printfn "%A"
Second way:
Seq.initInfinite (fun x -> x + 1) |> printfn "%A"
There are two key differences between the two:
First, unfold
lets you keep some state between steps while initInfinite
only gives you the index of the item that you are generating, so you need to have a way of producing a value based on the index.
Second, unfold
lets you create sequences that are finite (by returning None
) while initInfinite
only creates infinite sequences (as the name suggests)
The unfold
function is more general than initInfinite
. To see this, we can easily implement initInfinite
using unfold
:
let initInfinite f =
Seq.unfold (fun n -> Some(f n, n + 1)) 0
In the other direction, the following example using unfold
creates a sequence where each element is larger than the previous one by some random number. It ends once the number gets above 100:
let rnd = System.Random()
Seq.unfold (fun last ->
let next = last + rnd.Next(10)
if last + next > 100 then None
else Some(last + next, last + next) ) 0
You cannot do this using initInfinite
- because you do not know what the previous value was and you cannot end the sequence.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.