Search code examples
f#yield

F# yield! (yieldbang) operator


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.


Solution

  • 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 note: 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.