F# — yield vs yield!

C# devel­op­ers should be famil­iar with the yield key­word that was intro­duced in C# 2.0, and you’ll be pleased to know that F# also has the yield key­word which works in con­junc­tion with F#’s equiv­a­lent of IEnu­mer­ablesequences.

You can cre­ate sequences in F# using sequence expres­sions:

image

In addi­tion, you can also use the yield! (pro­nounced yield bang) key­word to return a sub­se­quence which is merged into the final sequence. Using a rather con­trived exam­ple (sor­ry…) let’s com­pare the out­put of yield and yield!:

image

Look at how the sig­na­tures dif­fer for these two sequences:

image

and how the val­ues in the two sequences dif­fer too:

image

The yield! key­word is sim­i­lar to IEnumerable.SelectMany in its abil­i­ty to flat­ten a col­lec­tion of col­lec­tions but it’s far more pow­er­ful as you can mix and match it with oth­er yield/yield! state­ments and give you a lev­el of expres­sive­ness that IEnumerable.SelectMany does not.