We know Sequences in C# are lazy i.e. generator generates on demand (lazily one at a time), and terminate when reduction order terminates.
I am pretty much content with the C#’s implementation, but I came across two features (F# and ES2015 each) which I think are pretty interesting.
Two Way Generators in ES2015
The word “generator” thus is a misnomer in case of ES2015, as it can both produce and consume the data.
David Walsh explains the usage of the two way generators and shows it can be used to achieve async flow control. See Part 2 of his blog for real world usage where the URL request call are yielded as a promise (aka Task)
A two way generator + yielded promise(s) combines the best of both worlds to get really powerful and elegant sync(-looking) async flow control expression capabilities.
Yield Bang (yield !) in F#
This operator in many ways work like SelectMany for Lazy Sequences
Let us try to understand the yield! operator by comparing and understanding with a C# example first.
Say we want to print all nested files under a folder, one way to create a lazy sequence in C# would be to write something like below
See Line number 16-19, In F# we can replace these three line with something like
Yield! basically flattens, returns the sub-sequence and merge with the main sequence in order.
If there was a yield! operator in C# we could re-write the GetFiles function as
Here is the same code in F#, as always F# makes code more succinct and easy to use
I’d be happy to learn what all features other languages add on top of these. Please do share or point to docs if you know.