3 ms·
List comprehensions are actually set notation in disguise, so they’re quite powerful and compact. Haskell has them too. You can express the above as: [x * x f
by wenc 5y ago
List comprehensions are actually set notation in disguise, so they’re quite powerful and compact. Haskell has them too.
You can express the above as:
[x * x for x in [1, 2, 3, 4] if x < 10]
Which in set notation is {x^2 : x in (1, 2, .., 4), x < 10}.
- williamstein 5y agoThe list defined above is [1, 4, 9], but the one you just defined is [1, 4, 9, 16]. It's interesting how the shift in notation subtly confused the semantics of what's going on.
- wenc 5y agoGood point. I missed that and made a mistake. It should have been: [x * x for x in [1, 2, 3, 4] if x * x < 10] There is a subtle shift in semantics. The functional form defines a sequence of function applications whereas the list comp notation is more of a declaration.