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

ES2015 aka Javascript supports what is called two way generators. ES2015 generators can not only send data back to the consumer (one way – like C# does), but it can also accept data back from the consumer for the production of subsequent item.

Here “function * interrogate()” is Javascript’s way of saying that this function is a generator (analogous to how we say IEnumerable<T> in C#). The return type from generator is a structure type that consists of the return value and a boolean to represent if iteration is complete or not.

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! Directory.GetFiles(basePath)

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.