-
Notifications
You must be signed in to change notification settings - Fork 0
Problem 2: yield!
Vitaly Kamiansky edited this page Apr 9, 2018
·
1 revision
Consider the following function:
let generateSequence () =
let getNum num =
Seq.singleton num
seq{
yield! Seq.empty
|> Seq.append (
getNum 1)
|> Seq.append (
getNum 2)
|> Seq.append (
getNum 3)
}
The following c# line is used to test it.
MarkedComposite.generateSequence().AllowTake(2).Take(2).ToArray();
Of course, if we believe in miracles and expect getNum
to be called twice - we would be set for a disappointment. The function will first be called three times and then out of the whole generated sequence we would get the lucky two elements.
The implementation we are looking for is shown below.
let generateSequence () =
let getNum num =
Seq.singleton num
seq{
yield getNum 1
yield getNum 2
yield getNum 3
}
The lesson here is to always be mindful of the laziness status of the sequence that we are returning. For instance, the following code will also be acceptable. It will also only call getNum
twice.
let generateSequence () =
let getNum num =
Seq.singleton num
seq{
yield! Seq.empty
|> Seq.append (
seq{ yield! getNum 1})
|> Seq.append (
seq{ yield! getNum 2})
|> Seq.append (
seq{ yield! getNum 3})
}