A list comprehension is a function that takes in an Array, and outputs a different Array. Whereas predicates are pure functions that return
false, list comprehensions are very similar, with the goal to help reduce the amount of code required to write loops such as the
Pure loops with less code.
Many people sell list comprehensions coming from the Ruby or Python background as a way to do loops with less code. That misses the fundamental goal is to ensure purity. You can create pure functions using regular
while loops, just like you can use the
let keywords, yet still ensure the function is pure. However, they are quite imperative, and you can make mistakes easier. It also has "mutation mindset" such as mutating a list index or keeping track of a current value, which is ok but isn't how pure functions work.
In true functional programming, there are no loops, only recursion. We don't care about that, though, because we'll just use the functions that take care of those details for us.
The Big 3
In weight lifting, there is the concept of The Big 3. The Squat, Bench Press, and Deadlift. They are the core exercises, with ample sleep and protein, to become strong.
List comprehensions are no different. The Big 3 for them is
reduce. Here's a famous picture that helps visualize in pseudo code how they work using emoji 😂:
map([🐮, 🥔, 🐔, 🌽], cook) === [🍔, 🍟, 🍗, 🍿] filter([🍔, 🍟, 🍗, 🍿], isVegetarian) === [🍟, 🍿] reduce([🍔, 🍟, 🍗, 🍿], eat) === 💩
We'll cover them as well as using 3 additional functions they are used to build,
zip. Using these with predicates and other pure functions, you'll start to learn the basics of composing, and start to glimpse at how pure functions work well together in a more predictable fashion.
Finally, you'll gain a re-appreciation for an old friend, the
Array, and how powerful she is.
Note on Browser / Node Support
filter, etc. we'll be using Lodash instead of the built-in versions merely because the Lodash functions are safe and immutable, and Lodash is an extremely battle tested library. Additionally, the syntax for Lodash and Ramda is based on pure functions taking inputs whereas most Array methods are based on class methods which are subject to being impure because of them being defined on the mutable
Array.prototype. Remember the Trouble With Dots. Modifying class prototypes has fallen out of fashion and is now a moderate security vulnerability. Most modern browsers including Node have good parity on ensuring
map works the same in all browsers and engines. Thus you are welcome to use the native ones if you're so inclined.
For example, the map in Lodash only provides your function with the item in the Array. The native Array map however provides the item, the current index, and a reference to the original Array that is being iterated over. That index is very useful in some cases. Just be careful when you go
theArray is actually
undefined (see the Trouble With Array Access).