List understandings are nothing more than a syntactic sugar for the construction of lists, often from another list or through some well-defined rule.
These constructions were inspired by notation for the construction of assemblies and are extremely common in functional languages (which also comes from strong mathematical foundations).
It is important to note that the list comprehensions are different forms of manipulate lists, if compared to traditional loops (such as for
) or higher order functions such as map
, filter
, etc..
Despite this difference in the way it is manipulated, internally, the compiler will probably generate very similar structures for the three patterns mentioned above, since they are all based on iteration on elements of a list.
But of course some features may vary from language to language. Haskell, for example, handles lists created with list comprehensions so Lazy (as well as almost everything in the language). But Python, for example, also has that resource, treat them in ways ager, so that it also provides the calls generators expresions, who operate under lazy behavior.
It is considered a control structure like the for
? And finally, list comprehension is a loop?
On the language level, I wouldn’t say list understandings are a for
, since the for
is also a syntactic resource of the languages that implement it.
But deep down, patterns that "repeat" something in programming will always have an internal resemblance.
List understandings can, yes, be seen as a "loop" of expressions, since they iterate over a list. See, for example, this case, in Haskell:
Prelude> mult2 = (*) 2
Prelude> [mult2 i | i <- [1, 2, 3]]
[2, 4, 6]
It’s basically going through every element of the original list, [1, 2, 3]
and applying the function mult2
, so that generates the list [2, 4, 6]
.
Note that, beyond the syntactic difference, there is not much difference in doing so:
Prelude> mult2 = (*) 2
Prelude> fmap mult2 [1, 2, 3]
[2, 4, 6]
That uses the function fmap
to map the list elements by applying them to a function. Note that the result is the same.
Both examples can be seen as loops and, in fact, are implemented internally with some repetition mechanism.
List understandings are therefore a more "declarative" means of repeating things. Of course, a functional language prefers more phrase-oriented approaches than the traditional imperative approach, marked by the classic for
. Makes sense from the semantic point of view of language.
In the first line already won my vote of utility. I finished reading and was worth the upvote.
– Augusto Vasques
I voted for that phrase "List understandings are nothing more than a syntactic sugar for the construction of lists" surgically answers the question. Even those who are beginning to program understand the message.
– Augusto Vasques