17

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.

xlm
  • 6,854
  • 14
  • 53
  • 55
schgab
  • 521
  • 5
  • 19

1 Answers1

19

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.

Matten
  • 17,365
  • 2
  • 42
  • 64