As you saw in the last chapter, lists of values are enclosed in square brackets, and separated by commas. We can make lists of any type we want, but a list can only hold a single type. Here are some examples of different types of lists. Try creating them in ghci :
| | λ listOfNums = [1, 2, 3] |
| | λ listOfFloats = [1.1, 2.2, 3.3] |
| | λ listOfStrings = [ "hello" , "world" ] |
There’s also a special type of list that you’ve already used extensively: strings! In Haskell, regular strings are simply lists of characters. When you create a string using double quotes, it’s really just a nice way of writing a list of individual characters. We can see this for ourselves in ghci :
| | λ [ 'h' , 'e' , 'l' , 'l' , 'o' ] == "hello" |
| | True |
You’ll rarely, if ever, write strings using the normal list syntax. However, you will frequently use other list functions when working with strings. This also means that some of the functions you’ve already used, like the (<>) operator, are actually more general than you might have realized. For example, we can combine lists of other values just as well as strings:
| | λ [1,2,3] <> [4,5,6] |
| | [1,2,3,4,5,6] |
| | |
| | λ [ 'h' , 'e' ] <> "llo" |
| | "hello" |
| | |
| | λ [[1,2,3],[4,5,6]] <> [[7,8,9]] |
| | [[1,2,3],[4,5,6],[7,8,9]] |
You can get the nth element of a list using the (!!) operator. List indices start at 0:
| | λ words = [ "foo" , "bar" , "baz" , "fizz" , "buzz" ] |
| | words !! 0 |
| | "foo" |
| | λ words !! 4 |
| | "buzz" |
You need to be careful to not accidentally try to take an index that’s larger than the length of a list:
| | λ words !! 5 |
| | "*** Exception: Prelude.!!: index too large |
We’re not limited to just single values; you can also create lists of lists:
| | λ nums = [[1,3,5],[2,4],[0]] |
| | λ strings = [[ "hello" , "good morning" ], [ "so long" , "farewell" ]] |
We can create empty lists with just an opening and closing bracket, like this: [] .
A list can only hold a single type of value. Because of this, you can’t have a list with lists of different types. This would be an error, for example:
| | λ badList = [[1,2,3],[ "one" , "two" , "three" ]] |
Lists, like all other Haskell values, are immutable. Although you can’t change the value of a list, you can efficiently construct lists by prepending a new element to the start of an existing list. The process of adding a new element to the beginning of a list is called “cons-ing,” and the operator we use to add an element to the front of a list, (:) , is generally pronounced “cons” as in “construct.” This style of prepending an element to the beginning of a list is so ubiquitous that when someone says that they are “adding an element to a list” you should assume they are prepending it unless they say otherwise.
Let’s look at a couple of examples of constructing lists using (:) . Try typing out these examples yourself to see what the generated lists look like, and to get more used to creating lists.
| | λ 1 : [2,3] |
| | λ 1 : 2 : [3] |
| | λ 1 : 2 : 3 : [] |
| | λ 'h' : "ello" |
| | λ 'h' : 'e' : [ 'l' , 'l' , 'o' ] |
| | λ [1,2,3] : [] |
| | λ [1] : [2] : [3] : [] |
Although you’ve seen that you can append elements to a list with (<>) , it’s far more common in Haskell to build our lists by prepending elements with (:) . In fact, prepending elements is so common that it’s not unusual to see functions where an entire list is built backwards only to be reversed at the end before being returned. The reason for this is that in an immutable language, prepending an element to a list is much more efficient than appending an element to the end.
Later, here , you’ll learn how to create list-like data structures yourself, which will help you better understand the details of why prepending is more efficient than appending to lists.
However you approach creating a list, in the end it comes down to putting one element in front of another. When you add an element to the front of a list, we call the part that you are adding the head of the list. In fact, a common alternative phrase cons-ing is to push an element onto the head of a list . The list that you are adding the element onto becomes the tail .
| | head : tail |
The tail of a list is itself either any empty list, or a list with its own head and tail, so you can also look at a list as a series of heads preceding a final empty list:
| | head : tail = head : (head : (head : ... : [] )) |
Head and tail aren’t just the terms we use to talk about parts of a list. The head and tail functions let you deconstruct a list and get the first element and the rest of the elements back out of a list you’ve constructed. Let’s look at some examples of using head and tail so you can get a feel for how they work:
| | λ head [1,2,3] |
| | 1 |
| | λ tail [1,2,3] |
| | [2,3] |
| | λ head (tail [1,2,3]) |
| | 2 |
| | λ tail (tail [1,2,3]) |
| | [3] |
| | λ tail [1] |
| | [] |
The head and tail functions are quite useful when you need to get at different parts of a list that you’ve built, but some caution is necessary with these functions. Both head and tail are partial functions . A partial function is a function that doesn’t work for all of its possible inputs, and might raise a runtime exception or cause the program to crash. In the case of head and tail , these functions will cause a runtime exception if you use them on an empty list:
| | λ head [] |
| | *** Exception : Prelude .head: empty list |
| | λ tail [] |
| | *** Exception : Prelude .tail: empty list |
You’ll learn another way to get the head and tail of a list here that doesn’t risk raising these exceptions, and later in this book you’ll learn how to handle runtime exceptions. In the meantime, take care to make sure you check first to see if a list is empty before using these functions. You can check for an empty list with equality:
| | listIsEmpty list = |
| | if list == [] |
| | then putStrLn "this list is empty" |
| | else putStrLn ( "the first element of this list is: " <> show (head list)) |
Alternatively, you can use the null function, which will return True if a list is empty, and False otherwise:
| | listIsEmpty' list = |
| | if null list |
| | then putStrLn "this list is empty" |
| | else putStrLn ( "the first element of this list is: " <> show (head list)) |
Creating Lists Recursively
A common pattern in Haskell is to create lists by pushing a new value onto the head of a list that is created with a recursive function call. In the last chapter, you worked through a few examples of recursion and built some small recursive functions, but it’s worthwhile to spend a little bit of extra time diving into recursive list construction. As you’ll see later on in this chapter, there are some subtleties to the way that we construct lists recursively in Haskell that can substantially change the way your program runs.
When you’re creating a list recursively in this way, your base case will be a list, often the empty list [] , and you’ll add elements at each step of the recursion. If you haven’t used recursion in a while, remember that the base case is the end of the recursion . It’s how you know that you’re done, since the base case doesn’t make a recursive call. In most cases, it’s easiest to write recursive functions by figuring out the base case first. Let’s look at a simple example of a function that creates a countdown from a starting number using this technique:
| | countdown n = |
| | if n <= 0 then [] |
| | else n : countdown (n - 1) |
Load your module in ghci and try running it with a few different numbers to get a feel for it:
| | λ countdown 10 |
| | [10,9,8,7,6,5,4,3,2,1] |
In this example, you start with a base case where n is less than or equal to 0. In the base case, you return an empty list. If n is greater than zero, you construct a list by prepending the current element to a recursive call that decrements the variable. This is a bit different than some of the recursive examples that you saw in the last chapter, because you’re building up a value rather than reducing one.
To improve your intuition, let’s step through a small example by hand. We’ll start by calling countdown 3 . In the first step we prepend 3 to countdown (3 - 1) :
| | countdown 3 = |
| | if 3 <= 0 -- false |
| | then [] |
| | else 3 : countdown (3 - 1) |
If you keep expanding the calls to countdown you’d end up with something like this, which isn’t quite valid Haskell, but gives you a sense of what’s happening:
| | countdown 3 = |
| | if 3 <= 0 -- false |
| | then [] |
| | else 3 : ( |
| | if 2 <= 0 -- false |
| | then [] |
| | else 2 : ( |
| | if 1 <= 0 -- false |
| | then [] |
| | else 1 : ( |
| | if 0 <= 0 -- true |
| | then [] |
| | else undefined |
| | ))) |
Resolving all of the branches you’d end up with:
| | countdown 3 = 3 : 2 : 1 : [] |
This style of recursively constructed list can build very powerful functions. Let’s look at another example using recursively constructed lists to find the prime factors of an integer. Take some time to study this function and work through it the same way that you worked through countdown to better understand how it works.
| | factors num = |
| | factors' num 2 |
| | where |
| | factors' num fact |
| | | num == 1 = [] |
| | | (num `rem` fact) == 0 = fact : factors' (num `div` fact) fact |
| | | otherwise = factors' num (fact + 1) |
This recursive function follows a common pattern where our algorithm requires some initial seed value that we don’t want to require the user to pass in. To make our code more ergonomic to use, it’s common to implement most of the algorithm as a helper function in a let or where binding. The top level function will just call the helper function with the initial seed value.
In the case of factors we’re calculating the potential factors of a number starting from 2 and working our way up, so our starting value is 2. The recursive part of our function is handled in our helper function, factors’ .
The way our factoring algorithm works is that we start with a number we’d like to factor—in this case we’re calling it num —and a potential factor, which we’re calling fact . Our base case is when num is 1, which has no other factors, so we can stop trying to find any.
The recursive case of our factoring function has two branches. The first of our recursive cases happens if our candidate factor is indeed an actual factor of our current number. We can figure this out using the rem function, which gives us the remainder after dividing the current number by the candidate factor. If the remainder is 0 then we’ve found a factor. When we have found an actual factor, we need to do two things. First, we need to add our newly discovered factor to our list of found factors. Second, we need to recursively find the rest of our factors.
The way that we add the current number onto the list of factors might look a little surprising at first:
| | fact : factors' (num `div` fact) fact |
Remember that factors’ will always return a list, whether it’s an empty list when we encounter the base case, or a list with some factors in it if we’re in a recursive case. Since the return value of factors’ is a list, we can add our new factor by prepending it to the front of the list returned by our recursive call.
As for the recursive call, rather than just decrementing our number by one, we can save a lot of time by dividing out the factor we’ve just found. We don’t change the candidate factor in our recursive call, because some numbers might have the same candidate factor multiple times. For example, the factors of four are two and two.
That covers our recursive case when we’ve found a factor. In our last case, when we haven’t found a factor, we increment our candidate factor by one and try again. Eventually this will terminate because even if we have a prime number we’ll eventually count all the way up so that our candidate factor equals the number we’re trying to factor. In that case, the number will be divisible by itself and we’ll add it to our list of factors, and then immediately hit our base case.
Deconstructing Lists
Recursively deconstructing a list is another pattern, like recursively constructing one, that you’ll use frequently when writing Haskell applications. In a typical application you’ll have a base case where a list is empty and a recursive case that does some computation with the head of the list and passes an accumulated value to itself recursively. Let’s look at a concrete example by building a function that checks to see if the parentheses in a string are balanced (that there are the same number of opening and closing parentheses). Keep a copy of this function open, you’ll be refactoring it shortly:
| | isBalanced s = |
| | 0 == isBalanced' 0 s |
| | where |
| | isBalanced' count s |
| | | null s = count |
| | | head s == '(' = isBalanced' (count + 1) (tail s) |
| | | head s == ')' = isBalanced' (count - 1) (tail s) |
| | | otherwise = isBalanced' count (tail s) |
Just like the factors example, we start this function off by calling a helper function that takes an accumulator value; in this case, isBalanced’ takes a counter. The first thing that isBalanced’ does is use the null function, which returns True if a list is empty. In the case of an empty list we’re done and can return our accumulator. In the next two cases, we are destructuring the list to look at the head element; if it’s an opening or closing parenthesis we increment or decrement our count respectively. In all of the cases, we recursively call the function with the tail of the input string.
Traversing a list and accumulating a result, like we’ve done here, is a common enough problem that you might want to create an implementation of it that you can re-use. Let’s write a generic reduce function that provides the structure of recursion and then use it to re-implement isBalanced :
| | reduce func carryValue lst = |
| | if null lst then carryValue |
| | else |
| | let intermediateValue = func carryValue (head lst) |
| | in reduce func intermediateValue (tail lst) |
You’ll notice when you look at this code that it looks almost like a minimum viable example of what a recursive function should look like. In the Haskell community, when we’re talking about the essential behavior of a function or a datatype, without any extraneous business logic or implementation details, we sometimes refer to that as the shape of the function or data structure. In this case, we might say that this function has the shape of any general recursive function over a list. Try using reduce to re-implement your isBalanced , then compare your implementations to the example:
| | isBalanced str = 0 == reduce checkBalance 0 str |
| | where |
| | checkBalance count letter |
| | | letter == '(' = count + 1 |
| | | letter == ')' = count - 1 |
| | | otherwise = count |
Our new isBalanced function is a little shorter and much easier to read thanks to the fact that we’re able to focus on the logic at each step of recursion without having to manage the recursion itself. Factoring out recursion into its own function is a small payoff the first time we use it, but as you use the pattern repeatedly over a larger codebase you can start to benefit from the reduced effort of understanding recursion each and every time, and instead you can start thinking in terms of reduction.
The reduce function that you implemented is actually already available in Prelude, where it’s called foldl . The general term in Haskell for these functions that accumulate a value while recursing through a structure are called folds . Let’s look at another common fold function that’s part of the Prelude: foldr .
The foldl and foldr function names stand for “fold left” and “fold right” respectively. You can intuitively think of foldl as folding from left to right, and foldr as folding from right to left.
To understand this better, let’s look at an example of how to build foldr , alongside the previous reduce (now renamed foldl ) function. Both the foldr and foldl functions that we’re building are part of the standard set of functions that are in scope when you start a new Haskell program. This will confuse the compiler, which will want to know which instance of the function you’re intending to use. Later, here , you’ll learn more about how to manage library functions, but for now you can hide the default versions of these functions to prevent a collision:
| | module FoldExamples where |
| | import Prelude hiding ( foldl , foldr ) |
With the two functions no longer imported from the standard library, you are free to create your own implementation as you work through the rest of this chapter.
| | foldl func carryValue lst = |
| | if null lst |
| | then carryValue |
| | else foldl func (func carryValue (head lst)) (tail lst) |
| | |
| | foldr func carryValue lst = |
| | if null lst |
| | then carryValue |
| | else func (head lst) $ foldr func carryValue (tail lst) |
Comparing the implementations of foldr with your earlier reduce (aka foldl ) implementation, you’ll notice that they are broadly similar. They both return the accumulator on an empty list, and otherwise perform some destructuring and recursion. In the case of foldl we call the function that’s been passed in with the current carry value and the head of the list, and then pass that into a recursive call. In foldr , instead of passing our carry value directly into the function, we pass the result of our recursive call. It’s also worth noting that the order of arguments in the function that’s passed in reverses between the two functions.
For a more hands-on picture of what’s happening, let’s pretend to be the compiler and use some pseudo-Haskell to explore exactly what happens when we make a call to foldl . We’ll start with foldl (+) 0 [1,2,3] :
| | foldl (+) 0 [1,2,3] = |
| | if null [1,2,3] then 0 |
| | else foldl (+) (0 + 1) [2,3] |
| | |
| | foldl (+) (0 + 1) [2,3] = |
| | if null [2,3] then (0 + 1) |
| | else foldl (+) ((0 + 1) + 2) [3] |
| | |
| | foldl (+) ((0 + 1) + 2) [3] = |
| | if null [3] then ((0 + 1) + 2) |
| | else foldl (+) (((0 + 1) + 2) +3) [] |
| | |
| | foldl (+) (((0 + 1) + 2) + 3) [] |
| | if null [] then (((0 + 1) + 2) + 3) |
| | else undefined -- we'll never get here |
| | |
| | (((0 + 1) + 2) + 3) = 0 + 1 + 2 + 3 = 6 |
Looking at the way parentheses grow when you expand the function calls, you can see that we end up working our way left-to-right through the list. You might recognize the way the operations have been grouped from the previous chapter when you learned about operators and fixity . The foldl function is a left-associative fold.
If foldl is left associative then you might guess based on the name that foldr is a right-associative fold. Let’s step through an example of foldlr (+) 0 [1,2,3] to see if the guess is right:
| | foldr (+) 0 [1,2,3] = |
| | if null [1,2,3] then 0 |
| | else (1 + (foldr (+) 0 [2,3])) |
| | |
| | foldr (+) 0 [2,3] = |
| | if null [1,2,3] then 0 |
| | else (1 + (2 + (foldr (+) 0 [3]))) |
| | |
| | foldr (+) 0 [3] = |
| | if null [1,2,3] then 0 |
| | else (1 + (2 + (3 + (foldr (+) 0 [] )))) |
| | |
| | foldr (+) 0 [] = |
| | if null [1,2,3] then 0 |
| | else undefined -- false |
| | |
| | (1 + (2 + (3 + 0))) = 6 |
As you can see, based on the way that the operations have been grouped, foldr is indeed right associative.
| Use Your Folds |
|---|
|
| As you are exploring the ideas in this chapter, you may have more success using your own definitions of foldl and foldr . The versions provided by default are more flexible, and they can work with data structures other than lists. This sometimes causes errors when the compiler doesn’t know what kind of data structure it should be using. This is most likely to occur if you are writing code in a pointfree style. If you run into this problem, first try refactoring your code so that it isn’t pointfree. If that doesn’t help, you can use the implementations of foldl and foldr you just defined, or revisit this chapter after you’ve learned about type. |
Let’s look at another example that can help to highlight the difference in associativity between the two folds. You might recall in the last chapter we looked at left and right associativity of division to better understand associativity of operators. Let’s return to that example again, this time to explore the associativity of folds.
In that example, we learned that the normal division operator, (/) is left associative. We created a right-associative infix function, divide , and used that to see how left and right-associative operations gave us different results when doing repeated division:
| | λ divide = (/); infixr 9 `divide` |
| | |
| | λ 1 / 2 / 3 / 4 / 5 |
| | 8.333333333333333e-3 |
| | |
| | λ 1 `divide` 2 `divide` 3 `divide` 4 `divide` 5 |
| | 1.875 |
When we’re using folds, the operation that we’re passing in is treated as a normal function, and its associativity doesn’t impact the final result we get back. The associativity of the operation comes from the fold itself, rather than the function we pass in. You can see, for example, that we get the same result back from a call to foldl regardless of which division function we pass in:
| | λ foldl (/) 1 [1,2,3,4,5] |
| | 8.333333333333333e-3 |
| | |
| | λ foldl divide 1 [1,2,3,4,5] |
| | 8.333333333333333e-3 |
The same thing applies to foldr as well:
| | λ foldr (/) 1 [1,2,3,4,5] |
| | 1.875 |
| | |
| | λ foldr divide 1 [1,2,3,4,5] |
| | 1.875 |
Related to the associativity of the folds, another important difference between them is when in the call chain the initial element gets passed in. You can see this in practice with another small variation of our fold example. Let’s look at another right fold using division, and compare it to the result we get back repeatedly applying the divide function by hand:
| | λ foldr divide 1 [2,3,4,5] |
| | 0.5333333333333333 |
| | |
| | λ 1 `divide` 2 `divide` 3 `divide` 4 `divide` 5 |
| | 1.875 |
When you first see the difference between these two results, you might be somewhat surprised. If foldr is right associative and it’s applying the divide repeatedly, we would expect to get the same value that we get when we call divide ourselves—but we seem to be getting something quite different!
If you look back at your implementation of foldr you might notice the problem: when we’re dividing manually in this example, we have put our initial value at the beginning of the list of division, but in the implementation of foldr we apply the initial value last. Let’s try to do manual division again, taking this into account:
| | λ 2 `divide` 3 `divide` 4 `divide` 5 `divide` 1 |
| | 0.5333333333333333 |
With our starting value moved to the right place, we get the same result using manual repeated division as we do from the call to foldr . Now let’s look at foldl . Since it’s left associative, we’ll compare it to (/) :
| | λ foldl (/) 1 [2,3,4,5] |
| | 8.333333333333333e-3 |
| | |
| | λ 1 / 2 / 3 / 4 / 5 |
| | 8.333333333333333e-3 |
This time we’ve put the initial value on the left, and again gotten the same result from manually doing repeated division.
It can be hard to keep the differences between foldl and foldr in your head when you are writing code, so it helps to remember these points:
-
The l in foldl stands for left associative.
-
In a left fold, the initial value is applied first, at the left-hand side of the unrolled expression.
-
In a left fold the accumulator value is the first (left) argument of the function you pass in.
-
The r in foldr stands for right associative.
-
In a right fold, the initial value is applied last, at the right-hand side of an unrolled expression.
-
In a right fold, the accumulator is the second (right) argument of the function that you pass in.
In the next chapter , you’ll learn about how to look up the type of a function. Looking at the types is another easy way to remind yourself of the difference between the two folds.
Transforming List Elements
Folds are useful and extremely common in Haskell code, but sometimes instead of wanting to combine the elements of a list, you find yourself wanting to transform the elements of a list individually. Consider, for example, that you have a list of numbers and you want to double each of them. You could write this using manual recursion:
| | doubleElems :: [ Int ] -> [ Int ] |
| | doubleElems nums = |
| | if null nums |
| | then [] |
| | else |
| | let |
| | hd = head nums |
| | tl = tail nums |
| | in (2 * hd) : doubleElems tl |
Like folding, applying a function to every element in a list is something quite common and so we may want to factor out the common code to apply a function to elements of a list from the specific logic of our function, in this case doubling the value of an element. In Haskell, we call applying a function to all the elements in a list “mapping,” and the function we use is called map . The map function takes a function and applies it to every element in a list:
| | λ let incr x = x + 1 in map incr [1..3] |
| | [2,3,4] |
| | λ map (+2) [1..3] |
| | [3,4,5] |
| | λ map show [1..3] |
| | [ "1" , "2" , "3" ] |
You can even use map to apply a value to a list of functions:
| | λ map ($ 10) [(+ 1), (* 3), (`div` 5)] |
| | [11,30,2] |
To get a better feel for how mapping works, we can also implement our own map function. We’ll start by refactoring doubleElems to use a fold rather than manual recursion:
| | doubleElems = foldr doubleElem [] |
| | where |
| | doubleElem num lst = (2 * num) : lst |
In this refactored version of our code, we’ve created a helper function called doubleElem that multiplies each element by 2. Let’s take another refactoring step and, instead of passing in a number to multiply by, we’ll pass in a function that will do the multiplication:
| | doubleElems' elems = foldr (applyElem (*2)) [] elems |
| | where |
| | applyElem f elem accumulator = f elem : accumulator |
In this version, our new applyElem function is quite general, but it’s still only working on a single step of the fold. Let’s take another refactoring step by making the foldr part of our new map’ function:
| | map' f = foldr (applyElem f) [] |
| | where |
| | applyElem f elem accumulator = (f elem) : accumulator |
| | |
| | doubleWithMap elems = map' (*2) elems |
We can take this one step further and manually expand out our call to foldr , giving us a more readable map function:
| | map'' f xs = |
| | if null xs then [] |
| | else f (head xs) : map'' f (tail xs) |
Filtering List Elements
Folding and mapping will both allow you to work with all the elements in a list, but it’s common to find yourself only interested in a subset of items in the list. There are several functions in base that you’ll be introduced to throughout this book that will help you select specific items out of a list. For now, we’ll focus on one of the most general and useful of these, the filter function.
The filter function allows you to select elements from a list. To use it, provide a function that returns True for values that you want to keep, and False for values you want to discard. For example, if you wanted to find the sum of the first ten odd numbers you could use filter with the odd function, which returns True if a number is odd:
| | λ (foldr (+) 0 . filter odd) [0..10] |
| | 25 |
It’s common to combine functions like map , fold , and filter into a data processing pipeline. Combining these building blocks can make it easy to write complex data transformations. Let’s create an example by building a function, foodBudget , to help plan the food budget for a party.
We’ll start by defining a function, checkGuestList , which will let us provide a list of people who will be attending the party. We’ll make use of the built-in function elem that tells us if a value is an element of a list:
| | checkGuestList guestList name = |
| | name `elem` guestList |
Next, we’ll create a list of some friends and how much their favorite meal costs:
| | foodCosts = |
| | [( "Ren" , 10.00) |
| | ,( "George" , 4.00) |
| | ,( "Porter" , 27.50)] |
Finally, we’ll add a function to combine our guest list and our food cost list to find the budget we need for our party:
| | partyBudget isAttending = |
| | foldr (+) 0 . map snd . filter (isAttending . fst) |
The partyBudget function might be a bit hard to read when you first look at it, since we are composing several different functions, so let’s step through it for a simple dinner party and see what’s happening:
| | λ partyBudget (checkGuestList [ "Ren" , "Porter" ]) foodCosts |
| | 37.5 |
We’re passing in a guest list that contains two of our friends, Ren and Porter , along with a list that has food prices for all of our friends. If we expand all of our helper functions we’d end up with this:
| | partyBudget' = |
| | foldr (+) 0 |
| | . map snd |
| | . filter ( \ name -> fst name `elem` [ "Ren" , "Porter" ]) |
| | $ [( "Ren" , 10.00) ,( "George" , 4.00) ,( "Porter" , 27.50)] |
When we’re composing functions like this, we usually want to read right-to-left. In this case, we’ll start with our call to filter . We’ll call our filter function for each item in the list, keeping the items where it returned true:
| | λ fst ( "Ren" , 10.00) `elem` [ "Ren" , "Porter" ] |
| | True |
| | λ fst ( "George" , 4.00) `elem` [ "Ren" , "Porter" ] |
| | False |
| | λ fst ( "Porter" , 27.50) `elem` [ "Ren" , "Porter" ] |
| | True |
After filtering we’re left with a smaller filtered list:
| | λ :{ |
| | > filteredNames = |
| | > filter ( \ name -> (fst name) `elem` [ "Ren" , "Porter" ]) $ |
| | > [ ( "Ren" ,10.00) |
| | > , ( "George" ,4.00) |
| | > , ( "Porter" ,27.50)] |
| | > :} |
| | λ filteredNames |
| | [( "Ren" ,10.0),( "Porter" ,27.5)] |
Next, we pass our new filteredNames list into our transform function, map snd . This will transform our tuples by looking at the second element:
| | map snd [( "Ren" ,10.00),( "Porter" ,27.5)] |
| | = [snd ( "Ren" ,10.00), snd ( "Porter" ,27.5)] |
| | = [10.00,27.5] |
All that’s left to do is add up the prices of our two guests’ favorite meals:
| | λ foldr (+) 0 [10.0,27.5] |
| | 37.5 |
Pure functional data processing functions made by composing maps, filters, and folds can be extremely effective ways of quickly writing expressive and effective Haskell code. As you spend more time with the language and become more comfortable with function composition and Haskell idioms you will be able to quickly read and write functions like this without the need to manually break down each step of the processing pipeline.
Building Lists with Comprehensions
It’s also possible to represent combinations of map and filter using List Comprehensions . List comprehensions provide an alternate syntax for building lists with maps and filters, and can sometimes make otherwise complex code much easier to read.
The basic syntax for a list comprehension looks like this:
| | double = [2 * number | number <- [0..10]] |
A list comprehension is an expression inside of square brackets, like a list, but it uses a pipe to separate out an expression from some conditionals, like a piece-wise function. In the double example, you can see the expression 2 * number on the left-hand side of the pipe. On the right-hand side of the pipe, we can select items from a list, like you would do with a map , and filter items out like you would do with a filter . If you wanted to double only odd numbers, for example, you could say:
| | doubleOdds = [2 * number | number <- [0..10], odd number] |
In this example, you’ve added a new predicate that will limit the elements that get pulled out of the list.
Functions on one list and with just a single predicate can sometimes look nicer written as list comprehensions, but they are also easy to write in the data pipeline style that you’ve already seen:
| | doubleOdds = map ( \ number -> 2 * number) . filter odd $ [0..10] |
Where list comprehensions start to really shine is when you have several lists that you want to work with, and many different filters. Let’s start with an illustrative example by building a function that will take two lists of numbers and will return a list of pairs of elements in the first list that are also in the second list, paired with odd elements of the second list. We’ll start by implementing this without using a list comprehension:
| | pairs as bs = |
| | let as' = filter (`elem` bs) as |
| | bs' = filter odd bs |
| | mkPairs a = map ( \ b -> (a,b)) bs' |
| | in concat $ map mkPairs as' |
| | λ pairs [1..10] [2..5] |
| | [(2,3),(2,5),(3,3),(3,5),(4,3),(4,5),(5,3),(5,5)] |
Now let’s look at the list comprehension version and compare it to the original version:
| | pairs as bs = |
| | [(a,b) | a <- as, b <- bs, a `elem` bs, odd b] |
The list comprehension version is not only much shorter, but it also gives us much more declarative-looking code. Instead of having to use filters to create intermediate lists that we then map over, the list comprehension version lets us more clearly state what we want: “pairs of a and b, where a comes from the list of as, and b comes from the list of bs, where a is an element of bs, and b is odd”.
To better see how we might make use of list comprehensions in practice, let’s go back to our dinner party budgeting function and imagine we wanted to expand it to account for the fact that most guests may want to eat more than one dish. Instead of including a price for the guest’s favorite meal, we’ll instead get a list of a guest and the food they’ve requested. We’ll also take two new functions. First, willEat will take a guest’s name and a food, and will return true if the guest might want to eat that food. Second, foodCost will take a food and return its price.
To calculate our budget now, we want to go through the list of all the guests that are attending and, for each food that we’ll be serving, add the cost for that food if the guest might eat it. Building this as a simple pipeline with map , filter , and fold could get quite complicated, but as you’ve just learned we can use list comprehensions to help simplify these types of functions.
Using a list comprehension we can tersely express our new party budget calculator:
| | partyBudget isAttending willEat foodCost guests = |
| | foldl (+) 0 $ |
| | [ foodCost food |
| | | guest <- map fst guests |
| | , food <- map snd guests |
| | , willEat guest food |
| | , isAttending guest |
| | ] |
Take particular note of the fact that, unlike previous examples of list comprehensions, in this example, we’re extracting a named element, guest , out of a list but not using it in the final list. Using list comprehensions can be a great way of expressing list processing code where you need to filter elements in one list based on a subset of elements from another list.
Using list comprehensions can be a handy way of expressing more complicated pipelines succinctly and without having to create many intermediate values. When you are writing list processing code it’s useful to experiment with list comprehensions to see if they can help you simplify your code.
Folds and comprehensions make it easy for you to combine elements of a single list, but what should you do if you want to combine two different lists? Consider that you have a list of numbers and a list of roman numeral representations of the numbers. If you wanted to associate the number with its roman numeral representation you might first try to use a list comprehension, like the following example:
| | λ [(num,str) | num <- [1,2,3], str <- [ "I" , "II" , "III" ]] |
| | [(1, "I" ),(1, "II" ),(1, "III" ) |
| | ,(2, "I" ),(2, "II" ),(2, "III" ) |
| | ,(3, "I" ),(3, "II" ),(3, "III" )] |
That won’t work! List comprehensions are useful when we want all of the permutations of our lists, but we only want to match the first element. You can implement a function yourself to do this. Think about how you might write a function named combineLists that takes two lists and returns a list of tuples, like in this example:
| | λ combineLists [1..5] [ "I" , "II" , "III" , "IV" , "V" , "VI" , "VII" ] |
| | [(1, "I" ),(2, "II" ),(3, "III" ),(4, "IV" ),(5, "V" )] |
One way you could implement a function like that is to use an explicit recursion, like in this example:
| | combineLists as bs = |
| | let |
| | a = head as |
| | b = head bs |
| | as' = tail as |
| | bs' = tail bs |
| | in if null as || null bs |
| | then [] |
| | else (a,b) : combineLists as' bs' |
Just like with map and the fold functions, there is already a standard library function that does exactly what combineLists does, and it’s named zip . Try using your combineLists function with several contrived examples, and then use zip for the same examples to demonstrate to yourself that they are doing the same thing.
Combining lists into a tuple isn’t generally very useful by itself, but zip can be combined with map and foldr to build much more sophisticated applications. Imagine, for example, that you had two lists of numbers and you wanted to figure out the sum of each pair of elements from two lists. Try copying the next example:
| | pairwiseSum xs ys = |
| | let sumElems pairs = |
| | let a = fst pairs |
| | b = snd pairs |
| | in a + b |
| | in map sumElems $ zip xs ys |
Alternatively, we could use the uncurry function, which makes it easy to apply a function of two elements to a tuple:
| | pairwiseSum xs ys = map (uncurry (+)) $ zip xs ys |
Run your new function with several examples, like this one:
| | λ pairwiseSum [1..5] [6..10] |
| | [7,9,11,13,15] |