If you’re the horrible sort of person who doesn’t read introductions, you might want to go back and read the last section anyway—it explains how to use this book, as well as how to load functions with GHC.

First, let’s start GHC’s interactive mode and call some functions, so we can get a very basic feel for Haskell. Open a terminal and type ghci . You will be greeted with something like this:

GHCi, version 8.0.1: http://www.haskell.org/ghc/  :? for help
Prelude>

Note

GHCi’s default prompt is Prelude> , but we’ll be using ghci> as our prompt for the examples in this book. To make your prompt match the book’s, enter :set prompt "ghci> " into GHCi. If you don’t want to do this every time you run GHCi, create a file called .ghci in your home folder and set its contents to :set prompt "ghci> " .

Congratulations, you’re in GHCi! Now let’s try some simple arithmetic:

ghci> 2 + 15
17
ghci> 49 * 100
4900
ghci> 1892 - 1472
420
ghci> 5 / 2
2.5

image with no caption

If we use several operators in one expression, Haskell will execute them in an order that takes into account the precedence of the operators. For instance, * has higher precedence than - , so 50 * 100 - 4999 is treated as (50 * 100) - 4999 .

We can also use parentheses to explicitly specify the order of operations, like this:

ghci> (50 * 100) - 4999
1
ghci> 50 * 100 - 4999
1
ghci> 50 * (100 - 4999)
-244950

Pretty cool, huh? (Yeah, I know it’s not, yet, but bear with me.)

One pitfall to watch out for is negative number constants. It’s always best to surround these with parentheses wherever they occur in an arithmetic expression. For example, entering 5 * -3 will make GHCi yell at you, but entering 5 * (-3) will work just fine.

Boolean algebra is also straightforward in Haskell. Like many other programming languages, Haskell has the Boolean values True and False , and uses the && operator for conjunction (Boolean and ), the || operator for disjunction (Boolean or ), and the not operator to negate a True or False value:

ghci> True && False
False
ghci> True && True
True
ghci> False || True
True
ghci> not False
True
ghci> not (True && True)
False

We can test two values for equality or inequality with the == and /= operators, like this:

ghci> 5 == 5
True
ghci> 1 == 0
False
ghci> 5 /= 5
False
ghci> 5 /= 4
True
ghci> "hello" == "hello"
True

Watch out when mixing and matching values, however! If we enter something like 5 + "llama" , we get the following error message:

No instance for (Num [Char]) arising from the use of `+'
In the expression: 5 + "llama"
In an equation for `it': it = 5 + "llama"

What GHCi is telling us here is that "llama" is not a number, so it does not know how to add it to 5. The + operator expects both of its inputs to be numbers.

On the other hand, the == operator works on any two items that can be compared, with one catch: they both have to be of the same type. For instance, if we tried entering True == 5 , GHCi would complain.

Note

5 + 4.0 is a valid expression, because although 4.0 isn’t an integer, 5 is sneaky and can act like either an integer or a floating-point number. In this case, 5 adapts to match the type of the floating-point value 4.0 .

We’ll take a closer look at types a bit later.

Calling Functions

image with no caption

You may not have realized it, but we’ve actually been using functions this whole time. For instance, * is a function that takes two numbers and multiplies them. As you’ve seen, we apply (or call ) it by sandwiching it between the two numbers we want to multiply. This is called an infix function.

Most functions, however, are prefix functions. When calling prefix functions in Haskell, the function name comes first, then a space, then its parameters (also separated by spaces). As an example, we’ll try calling one of the most boring functions in Haskell, succ :

ghci> succ 8
9

The succ function takes one parameter that can be anything that has a well-defined successor, and returns that value. The successor of an integer value is just the next higher number.

Now let’s call two prefix functions that take multiple parameters, min and max :

ghci> min 9 10
9
ghci> min 3.4 3.2
3.2
ghci> max 100 101
101

The min and max functions each take two parameters that can be put in some order (like numbers!), and they return the one that’s smaller or larger, respectively.

Function application has the highest precedence of all the operations in Haskell. In other words, these two statements are equivalent.

ghci> succ 9 + max 5 4 + 1
16
ghci> (succ 9) + (max 5 4) + 1
16

This means that if we want to get the successor of 9 * 10 , we couldn’t simply write

ghci> succ 9 * 10

Because of the precedence of operations, this would evaluate as the successor of 9 (which is 10) multiplied by 10, yielding 100. To get the result we want, we need to instead enter

ghci> succ (9 * 10)

This returns 91.

If a function takes two parameters, we can also call it as an infix function by surrounding its name with backticks ( ` ). For instance, the div function takes two integers and executes an integral division, as follows:

ghci> div 92 10
9

However, when we call it like that, there may be some confusion as to which number is being divided by which. By using backticks, we can call it as an infix function, and suddenly it seems much clearer:

ghci> 92 `div` 10
9

Many programmers who are used to imperative languages tend to stick to the notion that parentheses should denote function application, and they have trouble adjusting to the Haskell way of doing things. Just remember, if you see something like bar (bar 3) , it means that we’re first calling the bar function with 3 as the parameter, then passing that result to the bar function again. The equivalent expression in C would be something like bar(bar(3)) .

Baby’s First Functions

image with no caption

The syntax of a function definition is similar to that of a function call: the function name is followed by parameters, which are separated by spaces. But then the parameter list is followed by the = operator, and the code that makes up the body of the function follows that.

As an example, we’ll write a simple function that takes a number and multiplies it by two. Open up your favorite text editor and type in the following:

doubleMe x = x + x

Save this file as baby.hs . Now run ghci , making sure that baby.hs is in your current directory. Once in GHCi, enter :l baby to load the file. Now we can play with our new function:

ghci> :l baby
[1 of 1] Compiling Main             ( baby.hs, interpreted )
Ok, modules loaded: Main.
ghci> doubleMe 9
18
ghci> doubleMe 8.3
16.6

Because + works on integers as well as on floating point numbers (indeed, on anything that can be considered a number), our function also works with any of these types.

Now let’s make a function that takes two numbers, multiplies each by two, then adds them together. Append the following code to baby.hs :

doubleUs x y = x * 2 + y * 2

Note

Functions in Haskell don’t have to be defined in any particular order, so it doesn’t matter which function comes first in the baby.hs file.

Now save the file, and enter :l baby in GHCi to load your new function. Testing this function yields predictable results:

ghci> doubleUs 4 9
26
ghci> doubleUs 2.3 34.2
73.0
ghci> doubleUs 28 88 + doubleMe 123
478

Functions that you define can also call each other. With that in mind, we could redefine doubleUs in the following way:

doubleUs x y = doubleMe x + doubleMe y

This is a very simple example of a common pattern you will see when using Haskell: Basic, obviously correct functions can be combined to form more complex functions. This is a great way to avoid code repetition. For example, what if one day mathematicians figure out that 2 and 3 are actually the same, and you have to change your program? You could just redefine doubleMe to be x + x + x , and since doubleUs calls doubleMe , it would now also automatically work correctly in this strange new world where 2 is equal to 3.

Now let’s write a function that multiplies a number by 2, but only if that number is less than or equal to 100 (because numbers bigger than 100 are big enough as it is!).

doubleSmallNumber x = if x > 100
                        then x
                        else x*2

This example introduces Haskell’s if statement. You’re probably already familiar with if statements from other languages, but what makes Haskell’s unique is that the else part is mandatory.

Programs in imperative languages are essentially a series of steps that the computer executes when the program is run. When there is an if statement that doesn’t have a corresponding else , and the condition isn’t met, then the steps that fall under the if statement don’t get executed. Thus, in imperative languages, an if statement can just do nothing.

On the other hand, a Haskell program is a collection of functions. Functions are used to transform data values into result values, and every function should return some value, which can in turn be used by another function. Since every function has to return something, this implies that every if has to have a corresponding else . Otherwise, you could write a function that has a return value when a certain condition is met but doesn’t have one when that condition isn’t met! Briefly: Haskell’s if is an expression that must return a value, and not a statement.

Let’s say we want a function that adds one to every number that would be produced by our previous doubleSmallNumber function. The body of this new function would look like this:

doubleSmallNumber' x = (if x > 100 then x else x*2) + 1

Note the placement of the parentheses. If we had omitted them, the function would only add one if x is less than or equal to 100. Also note the apostrophe ( ' ) at the end of the function’s name. The apostrophe doesn’t have any special meaning in Haskell’s syntax, which means it’s a valid character to use in a function name. We usually use ' to denote either a strict version of a function (i.e., one that isn’t lazy), or a slightly modified version of a function or variable with a similar name.

Since ' is a valid character for function names, we can write a function that looks like this:

conanO'Brien = "It's a-me, Conan O'Brien!"

There are two things to note here. The first is that we didn’t capitalize Conan in the name of the function. In Haskell, functions can’t begin with capital letters. (We’ll see why a bit later.) The second thing to note is that conanO'Brien doesn’t take any parameters. This means that it's not a function, but a definition or a name . Because we cannot change what names (or functions) mean once we have defined them, conanO'Brien and the string "It's a-me, Conan O'Brien!" can be used interchangeably.

An Intro to Lists

image with no caption

Lists in Haskell are homogeneous data structures, which means they store several elements of the same type. We can have a list of integers or a list of characters, for example, but we can’t have a list made up of both integers and characters.

Lists are surrounded by square brackets, and the list values are separated by commas:

ghci> let lostNumbers = [4,8,15,16,23,42]
ghci> lostNumbers
[4,8,15,16,23,42]

Note

Use the let keyword to define a name in GHCi. Entering let a = 1 in GHCi is equivalent to writing a = 1 in a script, then loading it with :l .

Concatenation

One of the most common operations when working with lists is concatenation. In Haskell, this is done using the ++ operator:

ghci> [1,2,3,4] ++ [9,10,11,12]
[1,2,3,4,9,10,11,12]
ghci> "hello" ++ " " ++ "world"
"hello world"
ghci> ['w','o'] ++ ['o','t']
"woot"

Note

In Haskell, strings are really just lists of characters. For example, the string "hello" is actually the same as the list ['h','e','l','l','o'] . Because of this, we can use list functions on strings, which is really handy.

Be careful when repeatedly using the ++ operator on long strings. When you put together two lists, Haskell has to walk through the entire first list (the one on the left side of ++ ). That’s not a problem when dealing with smaller lists, but appending something to the end of a list with fifty million entries is going to take a while.

However, adding something to the beginning of a list is a nearly instantaneous operation. We do this with the : operator (also called the cons operator):

ghci> 'A':" SMALL CAT"
"A SMALL CAT"
ghci> 5:[1,2,3,4,5]
[5,1,2,3,4,5]

Notice how in the first example, : takes a character and a list of characters (a string) as its arguments. Similarly, in the second example, : takes a number and a list of numbers. The first argument to the : operator always needs to be a single item of the same type as the values in the list it’s being added to.

The ++ operator, on the other hand, always takes two lists as arguments. Even if you’re only adding a single element to the end of a list with ++ , you still have to surround that item with square brackets, so Haskell will treat it like a list:

ghci> [1,2,3,4] ++ [5]
[1,2,3,4,5]

Writing [1,2,3,4] ++ 5 is wrong, because both parameters to ++ should be lists, and 5 isn’t a list; it’s a number.

Interestingly, in Haskell, [1,2,3] is just syntactic sugar for 1:2:3:[] . [] is an empty list. If we prepend 3 to that, it becomes [3] . Then if we prepend 2 to that, it becomes [2,3] , and so on.

Note

[] , [[]] and [[],[],[]] are all different things. The first is an empty list, the second is a list that contains one empty list, and the third is a list that contains three empty lists.

Accessing List Elements

If you want to get an element of a list by index, use the !! operator. As with most programming languages, the indices start at 0:

ghci> "Steve Buscemi" !! 6
'B'
ghci> [9.4,33.2,96.2,11.2,23.25] !! 1
33.2

However, if you try (say) to get the sixth element from a list that only has four elements, you’ll get an error, so be careful!

Lists Inside Lists

Lists can contain lists as elements, and lists can contain lists that contain lists, and so on. . . .

ghci> let b = [[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]]
ghci> b
[[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]]
ghci> b ++ [[1,1,1,1]]
[[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3],[1,1,1,1]]
ghci> [6,6,6]:b
[[6,6,6],[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]]
ghci> b !! 2
[1,2,2,3,4]

Lists within a list can be of different lengths, but they can’t be of different types. Just like you can’t have a list that has some characters and some numbers as elements, you also can’t have a list that contains some lists of characters and some lists of numbers.

Comparing Lists

Lists can be compared if the items they contain can be compared. When using < , <= , >= and > to compare two lists, they are compared in lexicographical order. This means that first the two list heads are compared, and if they’re equal, the second elements are compared. If the second elements are also equal, the third elements are compared, and so on, until differing elements are found. The order of the two lists is determined by the order of the first pair of differing elements.

For example, when we evaluate [3,4,2] < [3,4,3] , Haskell sees that 3 and 3 are equal, so it compares 4 and 4 . Those two are also equal, so it compares 2 and 3 . 2 is smaller than 3 , so it comes to the conclusion that the first list is smaller than the second one. The same goes for <= , >= , and > .

ghci> [3,2,1] > [2,1,0]
True
ghci> [3,2,1] > [2,10,100]
True
ghci> [3,4,2] < [3,4,3]
True
ghci> [3,4,2] > [2,4]
True
ghci> [3,4,2] == [3,4,2]
True

Also, a nonempty list is always considered to be greater than an empty one. This makes the ordering of two lists well defined in all cases, including when one is a proper initial segment of the other.

More List Operations

Here are some more basic list functions, followed by examples of their usage.

The head function takes a list and returns its head, or first element:

ghci> head [5,4,3,2,1]
5

The tail function takes a list and returns its tail. In other words, it chops off a list’s head:

ghci> tail [5,4,3,2,1]
[4,3,2,1]

The last function returns a list’s last element:

ghci> last [5,4,3,2,1]
1

The init function takes a list and returns everything except its last element:

ghci> init [5,4,3,2,1]
[5,4,3,2]

To help us visualize these functions, we can think of a list as a monster, like this:

image with no caption

But what happens if we try to get the head of an empty list?

ghci> head []
*** Exception: Prelude.head: empty list

Oh my—it blows up in our face! If there’s no monster, it doesn’t have a head. When using head , tail , last , and init , be careful not to use them on empty lists. This error cannot be caught at compile time, so it’s always good practice to take precautions against accidentally telling Haskell to give you elements from an empty list.

The length function takes a list and returns its length:

ghci> length [5,4,3,2,1]
5

The null function checks if a list is empty. If it is, it returns True , otherwise it returns False .

ghci> null [1,2,3]
False
ghci> null []
True

The reverse function reverses a list:

ghci> reverse [5,4,3,2,1]
[1,2,3,4,5]

The take function takes a number and a list. It extracts the specified number elements from the beginning of the list, like this:

ghci> take 3 [5,4,3,2,1]
[5,4,3]
ghci> take 1 [3,9,3]
[3]
ghci> take 5 [1,2]
[1,2]
ghci> take 0 [6,6,6]
[]

If we try to take more elements than there are in the list, Haskell just returns the entire list. If we take 0 elements, we get an empty list.

The drop function works in a similar way, only it drops (at most) the specified number of elements from the beginning of a list:

ghci> drop 3 [8,4,2,1,5,6]
[1,5,6]
ghci> drop 0 [1,2,3,4]
[1,2,3,4]
ghci> drop 100 [1,2,3,4]
[]

The maximum function takes a list of items that can be put in some kind of order and returns the largest element. The minimum function is similar, but it returns the smallest item:

ghci> maximum [1,9,2,3,4]
9
ghci> minimum [8,4,2,1,5,6]
1

The sum function takes a list of numbers and returns their sum. The product function takes a list of numbers and returns their product:

ghci> sum [5,2,1,6,3,2,5,7]
31
ghci> product [6,2,1,2]
24
ghci> product [1,2,5,6,7,9,2,0]
0

The elem function takes an item and a list of items and tells us if that item is an element of the list. It’s usually called as an infix function because it’s easier to read that way.

ghci> 4 `elem` [3,4,5,6]
True
ghci> 10 `elem` [3,4,5,6]
False

Texas Ranges

image with no caption

What if we need a list made up of the numbers between 1 and 20? Sure, we could just type them all out, but that’s not a solution for gentlemen who demand excellence from their programming languages. Instead, we’ll use ranges . Ranges are used to make lists composed of elements that can be enumerated , or counted off in order.

For example, numbers can be enumerated: 1, 2, 3, 4, and so on. Characters can also be enumerated: the alphabet is an enumeration of characters from A to Z. Names, however, can’t be enumerated. (What comes after “John?” I don’t know!)

To make a list containing all the natural numbers from 1 to 20, you can just type [1..20] . In Haskell, this is exactly the same as typing [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] . The only difference between the two is that writing out long enumeration sequences manually is stupid.

Here are a few more examples:

ghci> [1..20]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
ghci> ['a'..'z']
"abcdefghijklmnopqrstuvwxyz"
ghci> ['K'..'Z']
"KLMNOPQRSTUVWXYZ"

You can also specify a step between items in your range. What if we want a list of every even number between 1 and 20? Or every third number between 1 and 20? It’s simply a matter of separating the first two elements with a comma and specifying the upper limit:

ghci> [2,4..20]
[2,4,6,8,10,12,14,16,18,20]
ghci> [3,6..20]
[3,6,9,12,15,18]

While they are pretty convenient, ranges with steps aren’t always as smart as people expect them to be. For example, you can’t enter [1,2,4,8,16..100] and expect to get all the powers of 2 that are no greater than 100. For one thing, you can only specify a single step size. Also, some sequences that aren’t arithmetic can’t be specified unambiguously by giving only their first few terms.

Note

To make a list with all the numbers from 20 down to 1, you can’t just type [20..1] , you have to type [20,19..1] . When you use a range without steps (like [20..1] ), Haskell will start with an empty list and then keep increasing the starting element by one until it reaches or surpasses the end element in the range. Because 20 is already greater than 1, the result will just be an empty list.

You can also use ranges to make infinite lists by not specifying an upper limit. For example, let’s create a list containing the first 24 multiples of 13. Here’s one way to do it:

ghci> [13,26..24*13]
[13,26,39,52,65,78,91,104,117,130,143,156,169,
182,195,208,221,234,247,260,273,286,299,312]

But there’s actually a better way—using an infinite list:

ghci> take 24 [13,26..]
[13,26,39,52,65,78,91,104,117,130,143,156,169,182,
195,208,221,234,247,260,273,286,299,312]

Because Haskell is lazy , it won’t try to evaluate the entire infinite list immediately (which is good because it would never finish anyway). Instead, it will wait to see which elements you need to get from that infinite list. In the above example, it sees that you just want the first 24 elements, and it gladly obliges.

Here are a few functions that can be used to produce long or infinite lists:

  • cycle takes a list and replicates its elements indefinitely to form an infinite list. If you try to display the result, it will go on forever, so make sure to slice it off somewhere:

    ghci> take 10 (cycle [1,2,3])
    [1,2,3,1,2,3,1,2,3,1]
    ghci> take 12 (cycle "LOL ")
    "LOL LOL LOL "
  • repeat takes an element and produces an infinite list of just that element. It’s like cycling a list with only one element:

    ghci> take 10 (repeat 5)
    [5,5,5,5,5,5,5,5,5,5]
  • replicate is an easier way to create a list composed of a single item. It takes the length of the list and the item to replicate, as follows:

    ghci> replicate 3 10
    [10,10,10]

One final note about ranges: watch out when using them with floating-point numbers! Because floating-point numbers, by their nature, only have finite precision, using them in ranges can yield some pretty funky results, as you can see here:

ghci> [0.1, 0.3 .. 1]
[0.1,0.3,0.5,0.7,0.8999999999999999,1.0999999999999999]

I’m a List Comprehension

image with no caption

List comprehensions are a way to filter, transform, and combine lists.

They’re very similar to the mathematical concept of set comprehensions . Set comprehensions are normally used for building sets out of other sets. An example of a simple set comprehension is: { 2 · x | x ∈ N , x ≤ 10}. The exact syntax used here isn’t crucial—what’s important is that this statement says, “take all the natural numbers less than or equal to 10, multiply each one by 2, and use these results to create a new set.”

If we wanted to write the same thing in Haskell, we could do something like this with list operations: take 10 [2,4..] . However, we could also do the same thing using list comprehensions, like this:

ghci> [x*2 | x <- [1..10]]
[2,4,6,8,10,12,14,16,18,20]

Let’s take a closer look at the list comprehension in this example to better understand list comprehension syntax.

In [x*2 | x <- [1..10]] , we say that we draw our elements from the list [1..10] . [x <- [1..10]] means that x takes on the value of each element that is drawn from [1..10] . In other words, we bind each element from [1..10] to x . The part before the vertical pipe ( | ) is the output of the list comprehension. The output is the part where we specify how we want the elements that we’ve drawn to be reflected in the resulting list. In this example, we say that we want each element that is drawn from the list [1..10] to be doubled.

This may seem longer and more complicated than the first example, but what if we want to do something more complex than just doubling these numbers? This is where list comprehensions really come in handy.

For example, let’s add a condition (also called a predicate ) to our comprehension. Predicates go at the end of the list comprehension and are separated from the rest of the comprehension by a comma. Let’s say we want only the elements which, after being doubled, are greater than or equal to 12:

ghci> [x*2 | x <- [1..10], x*2 >= 12]
[12,14,16,18,20]

What if we want all numbers from 50 to 100 whose remainder when divided by 7 is 3? Easy:

ghci> [ x | x <- [50..100], x `mod` 7 == 3]
[52,59,66,73,80,87,94]

Note

Weeding out parts of lists using predicates is also called filtering .

Now for another example. Let’s say we want a comprehension that replaces every odd number greater than 10 with "BANG!" , and every odd number less than 10 with "BOOM!" . If a number isn’t odd, we throw it out of our list. For convenience, we’ll put that comprehension inside a function so we can easily reuse it:

boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]

Note

Remember, if you’re trying to define this function inside GHCi, you have to include a let before the function name. However, if you’re defining this function inside a script and then loading that script into GHCi, you don’t have to mess around with let .

The odd function returns True when passed an odd number, otherwise it returns False . The element is included in the list only if all the predicates evaluate to True .

ghci> boomBangs [7..13]
["BOOM!","BOOM!","BANG!","BANG!"]

We can include as many predicates as we want, all separated by commas. For instance, if we wanted all numbers from 10 to 20 that are not 13, 15 or 19, we’d do:

ghci> [ x | x <- [10..20], x /= 13, x /= 15, x /= 19]
[10,11,12,14,16,17,18,20]

Not only can we have multiple predicates in list comprehensions, we can also draw values from several lists. When drawing values from several lists, every combination of elements from these lists is reflected in the resulting list:

ghci> [x+y | x <- [1,2,3], y <- [10,100,1000]]
[11,101,1001,12,102,1002,13,103,1003]

Here, x is drawn from [1,2,3] and y is drawn from [10,100,1000] . These two lists are combined in the following way. First, x becomes 1 , and while x is 1 , y takes on every value from [10,100,1000] . Because the output of the list comprehension is x+y , the values 11 , 101 , and 1001 are added to the beginning of the resulting list ( 1 is added to 10 , 100 , and 1000 ). After that, x becomes 2 and the same thing happens, resulting in the elements 12 , 102 , and 1002 being added to the resulting list. The same goes when x draws the value 3 .

In this manner, each element x from [1,2,3] is combined with each element y from [10,100,1000] in all possible ways, and x+y is used to make the resulting list from those combinations.

Here’s another example: if we have two lists, [2,5,10] and [8,10,11] , and we want to get the products of all possible combinations of numbers in those lists, we could use the following comprehension:

ghci> [ x*y | x <- [2,5,10], y <- [8,10,11]]
[16,20,22,40,50,55,80,100,110]

As expected, the length of the new list is 9. Now, what if we wanted all possible products that are more than 50? We can just add another predicate:

ghci> [ x*y | x <- [2,5,10], y <- [8,10,11], x*y > 50]
[55,80,100,110]

For epic hilarity, let’s make a list comprehension that combines a list of adjectives and a list of nouns.

ghci> let nouns = ["hobo","frog","pope"]
ghci> let adjectives = ["lazy","grouchy","scheming"]
ghci> [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]
["lazy hobo","lazy frog","lazy pope","grouchy hobo","grouchy frog",
"grouchy pope","scheming hobo","scheming frog","scheming pope"]

We can even use list comprehensions to write our own version of the length function! We’ll call it length' . This function will replace every element in a list with 1 , then add them all up with sum , yielding the length of the list.

length' xs = sum [1 | _ <- xs]

Here we use underscore ( _ ) as a temporary variable to store the items as we draw them from the input list, since we don’t actually care about the values.

Remember, strings are lists too, so we can use list comprehensions to process and produce strings. Here’s an example of a function that takes a string and removes all the lowercase letters from it:

removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]

The predicate here does all the work. It says that the character will be included in the new list only if it’s an element of the list ['A'..'Z'] . We can load the function in GHCi and test it out:

ghci> removeNonUppercase "Hahaha! Ahahaha!"
"HA"
ghci> removeNonUppercase "IdontLIKEFROGS"
"ILIKEFROGS"

You can also create nested list comprehensions if you’re operating on lists that contain lists. For example, let’s take a list that contains several lists of numbers and remove all the odd numbers without flattening the list:

ghci> let xxs = [[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]]
ghci> [ [ x | x <- xs, even x ] | xs <- xxs]
[[2,2,4],[2,4,6,8],[2,4,2,6,2,6]]

Here the output of the outer list comprehension is another list comprehension. A list comprehension always results in a list of something, so we know that the result here will be a list of lists of numbers.

Note

You can split list comprehensions across several lines to improve their readability. If you’re not in GHCi, this can be a great help, especially when dealing with nested comprehensions.

Tuples

image with no caption

Tuples are used to store several heterogeneous elements as a single value.

In some ways, tuples are a lot like lists. However, there are some fundamental differences. First, as mentioned, tuples are heterogeneous. This means that a single tuple can store elements of several different types. Second, tuples have a fixed size—you need to know how many elements you’ll be storing ahead of time.

Tuples are surrounded by parentheses, and their components are separated by commas:

ghci> (1, 3)
(1,3)
ghci> (3, 'a', "hello")
(3,'a',"hello")
ghci> (50, 50.4, "hello", 'b')
(50,50.4,"hello",'b')

Using Tuples

As an example of when tuples would be useful, let’s think about how we’d represent a two-dimensional vector in Haskell. One way would be to use a two item list, in the form of [x,y] . But suppose we wanted to make a list of vectors, to represent the corners of a two-dimensional shape in a coordinate plane. We could just create a list of lists, like this: [[1,2],[8,11],[4,5]] .

The problem with this method, however, is that we could also make a list like [[1,2],[8,11,5],[4,5]] and try to use it in the place of a list of vectors. Even though it doesn’t make sense as a list of vectors, Haskell has no problem with this list appearing wherever the previous list can, since both are of the same type (a list of lists of numbers). This could make it more complicated to write functions to manipulate vectors and shapes.

In contrast, a tuple of size two (also called a pair ) and a tuple of size three (also called a triple ) are treated as two distinct types, which means a list can’t be composed of both pairs and triples. This makes tuples much more useful for representing vectors.

We can change our vectors to tuples by surrounding them with parentheses instead of square brackets, like this: [(1,2),(8,11),(4,5)] . Now, if we try to mix pairs and triples, we get an error, like this:

ghci> [(1,2),(8,11,5),(4,5)]
<interactive>:1:8: error:
    Couldn't match expected type `(t, t1)'
        with actual type `(Integer, Integer, Integer)'
    In the expression: (8, 11, 5)
    In the expression: [(1, 2), (8, 11, 5), (4, 5)]
    In an equation for `it': it = [(1, 2), (8, 11, 5), (4, 5)]
    Relevant bindings include
        it :: [(t, t1)] (bound at <interactive>:1:1)

Haskell also considers tuples that have the same length but contain different types of data to be distinct types of tuples. For example, you can’t make a list of tuples like [(1,2),("One",2)] , because the first is a pair of numbers, and the second is a pair containing a string followed by a number.

Tuples can be used to easily represent a wide variety of data. For instance, if we wanted to represent someone’s name and age in Haskell, we could use a triple: ("Christopher", "Walken", 55) .

Remember, tuples are of a fixed size—you should only use them when you know in advance how many elements you’ll need. The reason tuples are so rigid in this way is that, as mentioned, the size of a tuple is treated as part of its type. Unfortunately, this means that you can’t write a general function to append an element to a tuple—you’d have to write a function for appending to a pair (to produce a triple), another one for appending to a triple (to produce a 4-tuple), another one for appending to a 4-tuple, and so on.

Like lists, tuples can be compared with each other if their components can be compared. However, unlike lists, you can’t compare two tuples of different sizes.

Although there are singleton lists, there’s no such thing as a singleton tuple. It makes sense when you think about it: a singleton tuple’s properties would simply be those of the value it contains, so distinguishing a new type wouldn’t give us any benefit.

Using Pairs

Storing data in pairs is very common in Haskell, and there are some useful functions in place to manipulate them. Here are two functions that operate on pairs:

  • fst takes a pair and returns its first component:

    ghci> fst (8, 11)
    8
    ghci> fst ("Wow", False)
    "Wow"
  • snd takes a pair and—surprise!—returns its second component:

    ghci> snd (8, 11)
    11
    ghci> snd ("Wow", False)
    False

Note

These functions only operate on pairs. They won’t work on triples, 4-tuples, 5-tuples, etc. We’ll go over extracting data from tuples in different ways a bit later.

The zip function is a cool way to produce a list of pairs. It takes two lists, then “zips” them together into one list by joining the matching elements into pairs. It’s a really simple function, but it can be very useful when you want to combine two lists in a particular way or traverse two lists simultaneously. Here’s a demonstration:

ghci> zip [1,2,3,4,5] [5,5,5,5,5]
[(1,5),(2,5),(3,5),(4,5),(5,5)]
ghci> zip [1..5] ["one", "two", "three", "four", "five"]
[(1,"one"),(2,"two"),(3,"three"),(4,"four"),(5,"five")]

Notice that because pairs can have different types in them, zip can take two lists that contain elements of different types. But what happens if the lengths of the lists don’t match?

ghci> zip [5,3,2,6,2,7,2,5,4,6,6] ["im","a","turtle"]
[(5,"im"),(3,"a"),(2,"turtle")]

As you can see in the above example, only as much of the longer list is used as needed—the rest is simply ignored. And because Haskell uses lazy evaluation, we can even zip finite lists with infinite lists:

ghci> zip [1..] ["apple", "orange", "cherry", "mango"]
[(1,"apple"),(2,"orange"),(3,"cherry"),(4,"mango")]

Finding the Right Triangle

Let’s wrap things up with a problem that combines tuples and list comprehensions. We’ll use Haskell to find a right triangle that fits all of these conditions:

  • The lengths of the three sides are all integers.

  • The length of each side is less than or equal to 10.

  • The triangle’s perimeter (the sum of the side lengths) is equal to 24.

image with no caption

A triangle is a right triangle if one of its angles is a right angle (a 90-degree angle). Right triangles have the useful property that if you square the lengths of the sides forming the right angle and then add those squares, that sum is equal to the square of the length of the side that’s opposite the right angle. In the picture, the sides that lie next to the right angle are labeled a and b , and the side opposite the right angle is labeled c . We call that side the hypotenuse .

As a first step, let’s generate all possible triples with elements that are less than or equal to 10:

ghci> let triples = [ (a,b,c) | c <- [1..10], a <- [1..10], b <- [1..10] ]

We’re drawing from three lists on the right-hand side of the comprehension, and the output expression on the left combines them into a list of triples. If you evaluate triples in GHCi, you’ll get a list that is 1,000 entries long, so we won’t show it here.

Next, we’ll filter out triples that don’t represent right triangles by adding a predicate that checks to see if the Pythagorean theorem ( a^2 + b^2 == c^2 ) holds. We’ll also modify the function to ensure that side a isn’t larger than the hypotenuse c , and that side b isn’t larger than side a :

ghci> let rightTriangles = [ (a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a],
a^2 + b^2 == c^2]

Notice how we changed the ranges in the lists that we draw values from. This ensures that we don’t check unnecessary triples, such as ones where side b is larger than the hypotenuse (in a right triangle, the hypotenuse is always the longest side). We also assumed that side b is never larger than side a . This doesn’t harm anything, because for every triple (a,b,c) with a^2 + b^2 == c^2 and b > a that is left out of consideration, the triple (b,a,c) is included—and is the same triangle, just with the legs reversed. (Otherwise, our list of results would contain pairs of triangles that are essentially the same.)

Note

In GHCi, you can’t break up definitions and expressions across multiple lines. In this book, however, we occasionally need to break up a single line so the code can all fit on the page. (Otherwise the book would have to be really wide, and it wouldn’t fit on any normal shelf—and then you’d have to buy bigger shelves!)

We’re almost done. Now, we just need to modify the function to only output the triangles whose perimeter equals 24:

ghci> let rightTriangles' = [ (a,b,c) | c <- [1..10],
 a <- [1..c], b <- [1..a], a^2 + b^2 == c^2, a+b+c == 24]
ghci> rightTriangles'
[(6,8,10)]

And there’s our answer! This is a common pattern in functional programming: you start with a certain set of candidate solutions, and successively apply transformations and filters to them until you’ve narrowed the possibilities down to the one solution (or several solutions) that you’re after.