Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# yield! (yieldbang) operator

Tags:

yield

f#

I am learning F# at the moment but I'm having a hard time understanding this:

let allPrimes =
let rec allPrimes' n = 
    seq {
        if isPrime n then
            yield n
        yield! allPrimes' (n + 1) }
allPrimes' 2

I am not able to figure out what the yield! operator exactly does even though I've read other simpler examples and it seems yield! returns an inner sequence.

like image 746
schgab Avatar asked Jul 06 '17 11:07

schgab


1 Answers

The yield bang operator merges the sub sequence produced by the called sequence expressions into the final sequence. Or in simpler words: it "flattens" the returned sequence to include the elements of the sub sequence in the final sequence.

For your example: Without the yield bang operator you would get something like

{ prime1 { prime2 { prime3 .... }}}

with the yield bang operator you get

{ prime1 prime2 prime3 ... }

where each { denotes a new sequence. Side node: The actual result from my first example would even include more sequences, as it would return sequences only containing sequences as the prime is only returned if n is prime.

like image 108
Matten Avatar answered Oct 01 '22 15:10

Matten