For-comprehension, a Scala language concept
Last updated
The for-comprehension is highly important syntatic enhancement in functional programming languages.
Becomes:
And
Becomes:
Even more interestingly, an 'if' guard may be available for some container types, such as:
Interestingly, this applies to pattern matching as well, which you can do inside for-comprehensions!
Background
Prior to Scala and F#, for-comprehensions were widely used in Haskell and XQuery. The key selling point is how much more concise they can make the code. There are numerous definitions of what they do (such as being 'a way to compose Monads'), However the most-straightforward way to see them is as something that lets you combine sequences of .map and .flatMap, as well as .collect/.withFilter in a very straight-forward way.
This can include the IO type of cats-effect, as well as simple types like Option Type and other container types like Lazy List or View.
What is cool in Scala is that often Option types can be combined with Iterables, allowing for very terse syntax.
for-comprehensions are in particular useful where code becomes unreadable due to a large number of chains of .map and .flatMap - and you just want to have everything in one column. This anti-pattern of unreadable chains of code is also known as callback hell (example).
Various names are given for for-comprehensions in different languages: do-notation in Haskell, await-async in JavaScript, list comprehensions in F#, generators in Python. Even SQL queries can be considered a form of for-comprehensions.