I’m a C# programmer, so I’ll be the first to admit that the functional programming world makes my head spin, but I find it very intriguing.
So I started investigating Haskell, a purely functional language (using a free book on this website: LearnYouAHaskell) and I was really impressed with Haskell’s list comprehensions. Even if you never use Haskell in your life, I think it’s still worth learning about some of its features. It broadens your thinking and shows that there is more to life than semicolons and curly braces.
Here are some list features and list comprehensions in Haskell. I’ll start simple and build from there. Let’s see what Haskell can do…
Haskell allows you to create a range as follows:
Ranges can also be constructed as follows, by specifying two items to start with, indicating the step. For example:
Finally, you can also create an infinite list, which will continue evaluating until you no longer need values (i.e. breaking out of a loop). For example:
Now that I’ve shown how to declare ranges, let’s briefly look at methods that interact with lists. “Head” takes the first item from a list.
“Tail” returns all the items except the “head”.
“Take” takes a specified number of items from the list.
Haskell also has a “cycle” method that cycles through the specified list infinitely. The following example takes the first 10 items from the list that cycles through 1,3,4:
|Now let’s have a look at list comprehensions. A list comprehension in Haskell adheres to the following basic format (select||input||condition). For example:|
You can type expressions in the “select” section as follows
(notice the “if”):
The condition (or predicate) section is applied to each item in the list you are selecting from. For example, the following statement returns only items where x mod 2 == 0.
Comprehensions can also allow multiple conditions:
Even cooler than multiple conditions are multiple inputs. Notice x and y below; the result is all possible combinations of the elements in x and y.
Or using a tuple:
This post was very high level, but I hope it gave an idea of the power of list comprehensions. Imagine the succinct and clear code you could write by using these features. I for one am quite excited to delve deeper into the Haskell world to see what else it can do!