A Haskell module is essentially a file that defines some functions, types, and type classes. A Has-kell program is a collection of modules.
A module can have many functions and types defined inside it, and it exports some of them. This means that it makes them available for the outside world to see and use.
Having code split up into several modules has many advantages. If a module is generic enough, the functions it exports can be used in a multitude of different programs. If your own code is separated into self-contained modules that don’t rely on each other too much (we also say they are loosely coupled ), you can reuse them later. Your code is more manageable when you split it into several parts.
The Haskell standard library is split into modules, and each of them contains functions and types that are somehow related and serve some common purpose. There are modules for manipulating lists, concurrent programming, dealing with complex numbers, and so on. All the functions, types, and type classes that we’ve dealt with so far are part of the Prelude module, which is imported by default.
In this chapter, we’re going to examine a few useful modules and their functions. But first, you need to know how to import modules.
Importing Modules
The syntax for importing modules in a Haskell script is import ModuleName . This must be done before defining any functions, so imports are usually at the top of the file. One script can import several modules—just put each import statement on a separate line.
An example of a useful module is Data.List , which has a bunch of functions for working with lists. Let’s import that module and use one of its functions to create our own function that tells us how many unique elements a list has.
import Data.List
numUniques :: (Eq a) => [a] -> Int
numUniques = length . nub
When you import Data.List , all the functions that Data.List exports become available; you can call them from anywhere in the script. One of those functions is nub , which takes a list and weeds out duplicate elements. Composing length and nub with length . nub produces a function that’s the equivalent of \xs -> length (nub xs) .
Note
To search for functions or to find out where they’re located, use Hoogle, which can be found at http://www.haskell.org/hoogle/ . It’s a really awesome Haskell search engine that allows you to search by function name, module name, or even type signature.
You can also get access to functions of modules when using GHCi. If you’re in GHCi and you want to be able to call the functions exported by Data.List , enter this:
ghci> :m + Data.List
If you want to access several modules from GHCi, you don’t need to enter :m + several times. You can load several modules at once, as in this example:
ghci> :m + Data.List Data.Map Data.Set
However, if you’ve loaded a script that already imports a module, you don’t need to use :m + to access that module. If you need only a couple of functions from a module, you can selectively import just those functions. For example, here’s how you could import only the nub and sort functions from Data.List :
import Data.List (nub, sort)
You can also choose to import all of the functions of a module except a few select ones. That’s often useful when several modules export functions with the same name and you want to get rid of the offending ones. Say you already have your own function called nub and you want to import all the functions from Data.List except the nub function. Here’s how to do that:
import Data.List hiding (nub)
Another way of dealing with name clashes is to do qualified imports . Consider the Data.Map module, which offers a data structure for looking up values by key. This module exports a lot of functions with the same name as Prelude functions, such as filter and null . So if we imported Data.Map and then called filter , Haskell wouldn’t know which function to use. Here’s how we solve this:
import qualified Data.Map
Now if we want to reference Data.Map ’s filter function, we must use Data.Map.filter . Entering just filter still refers to the normal filter we all know and love. But typing Data.Map in front of every function from that module is kind of tedious. That’s why we can rename the qualified import to something shorter:
import qualified Data.Map as M
Now to reference Data.Map ’s filter function, we just use M.filter .
As you’ve seen, the . symbol is used to reference functions from modules that have been imported as qualified, such as M.filter . We also use it to perform function composition. So how does Haskell know what we mean when we use it? Well, if we place it between a qualified module name and a function, without whitespace, it’s regarded as just referring to the imported function; otherwise, it’s treated as function composition.
Note
A great way to pick up new Haskell knowledge is to just click through the standard library documentation and explore the modules and their functions. You can also view the Haskell source code for each module. Reading the source code of some modules will give you a solid feel for Haskell.
Solving Problems with Module Functions
The modules in the standard libraries provide many functions that can make our lives easier when coding in Haskell. Let’s look at some examples of how to use functions from various Haskell modules to solve problems.
Counting Words
Suppose we have a string that contains a bunch of words, and we want to know how many times each word appears in the string. The first module function we’ll use is words from Data.List . The words function converts a string into a list of strings where each string is one word. Here’s a quick demonstration:
ghci> words "hey these are the words in this sentence"
["hey","these","are","the","words","in","this","sentence"]
ghci> words "hey these are the words in this sentence"
["hey","these","are","the","words","in","this","sentence"]
Then we’ll use the group function, which also lives in Data.List , to group together words that are identical. This function takes a list and groups adjacent elements into sublists if they are equal:
ghci> group [1,1,1,1,2,2,2,2,3,3,2,2,2,5,6,7]
[[1,1,1,1],[2,2,2,2],[3,3],[2,2,2],[5],[6],[7]]
But what happens if the elements that are equal aren’t adjacent in our list?
ghci> group ["boom","bip","bip","boom","boom"]
[["boom"],["bip","bip"],["boom","boom"]]
We get two lists that contain the string "boom" , even though we want all occurrences of some word to end up in the same list. What are we to do? Well, we could sort our list of words beforehand! For that, we’ll use the sort function, which hangs its hat in Data.List . It takes a list of things that can be ordered and returns a new list that is like the old one, but ordered from smallest to largest:
ghci> sort [5,4,3,7,2,1]
[1,2,3,4,5,7]
ghci> sort ["boom","bip","bip","boom","boom"]
["bip","bip","boom","boom","boom"]
Notice that the strings are put in an alphabetical order.
We have all the ingredients for our recipe. Now we just need to write it down. We’ll take a string, break it down into a list of words, sort those words, and then group them. Finally, we’ll use some mapping magic to get tuples like ("boom", 3) , meaning that the word "boom" occurs three times.
import Data.List
wordNums :: String -> [(String,Int)]
wordNums = map (\ws -> (head ws, length ws)) . group . sort . words
We used function composition to make our final function. It takes a string, such as "wa wa wee wa" , and then applies words to that string, resulting in ["wa","wa","wee","wa"] . Then sort is applied to that, and we get ["wa","wa","wa","wee"] . Applying group to this result groups adjacent words that are equal, so we get a list of lists of strings: [["wa","wa","wa"],["wee"]] . Then we map a function that takes a list and returns a tuple, where the first component is the head of the list and the second component is its length, over the grouped words. Our final result is [("wa",3),("wee",1)] .
Here’s how we could write this function without function composition:
wordNums xs = map (\ws -> (head ws,length ws)) (group (sort (words xs)))
Wow, parentheses overload! I think it’s easy to see how function composition makes this function more readable.
Needle in the Haystack
For our next mission, should we choose to accept it, we will make a function that takes two lists and tells us if the first list is wholly contained anywhere in the second list. For instance, the list [3,4] is contained in [1,2,3,4,5] , whereas [2,5] isn’t. We’ll refer to the list that’s being searched as the haystack and the list that we’re searching for as the needle .
For this escapade, we’ll use the tails function, which dwells in Data.List . tails takes a list and successively applies the tail function to that list. Here’s an example:
ghci> tails "party"
["party","arty","rty","ty","y",""]
ghci> tails [1,2,3]
[[1,2,3],[2,3],[3],[]]
At this point, it may not be obvious why we need tails at all. Another example will clarify this.
Let’s say that we’re searching for the string "art" inside the string "party" . First, we use tails to get all the tails of the list. Then we examine each tail, and if any one starts with the string "art" , we’ve found the needle in our haystack! If we were looking for "boo" inside "party" , no tail would start with the string "boo" .
To see if one string starts with another, we’ll use the isPrefixOf function, which is also found in Data.List . It takes two lists and tells us if the second one starts with the first one.
ghci> "hawaii" `isPrefixOf` "hawaii joe"
True
ghci> "haha" `isPrefixOf` "ha"
False
ghci> "ha" `isPrefixOf` "ha"
True
Now we just need to check if any tail of our haystack starts with our needle. For that, we can use the any function from Data.List . It takes a predicate and a list, and it tells us if any element from the list satisfies the predicate. Behold:
ghci> any (> 4) [1,2,3]
False
ghci> any (=='F') "Frank Sobotka"
True
ghci> any (\x -> x > 5 && x < 10) [1,4,11]
False
Let’s put these functions together:
import Data.List
isIn :: (Eq a) => [a] -> [a] -> Bool
needle `isIn` haystack = any (needle `isPrefixOf`) (tails haystack)
That’s all there is to it! We use tails to generate a list of tails of our haystack and then see if any of them starts with our needle. Let’s give it a test run:
ghci> "art" `isIn` "party"
True
ghci> [1,2] `isIn` [1,3,5]
False
Oh, wait a minute! It turns out that the function that we just made is already in Data.List ! Curses! It’s called isInfixOf , and it does the same work as our isIn function.
Caesar Cipher Salad
Gaius Julius Caesar has entrusted upon us an important task. We must transport a top-secret message to Mark Antony in Gaul. Just in case we get captured, we’re going to use some functions from Data.Char to be a bit sneaky and encode messages by using the Caesar cipher .
The Caesar cipher is a primitive method of encoding messages by shifting each character by a fixed number of positions in the alphabet. We can easily create a sort of Caesar cipher of our own, and we won’t constrict ourselves to the alphabet—we’ll use the whole range of Unicode characters.
To shift characters forward and backward in the alphabet, we’re going to use the Data.Char module’s ord and chr functions, which convert characters to their corresponding numbers and vice versa:
ghci> ord 'a'
97
ghci> chr 97
'a'
ghci> map ord "abcdefgh"
[97,98,99,100,101,102,103,104]
ord 'a' returns 97 because 'a' is the ninety-seventh character in the Unicode table of characters.
The difference between the ord values of two characters is equal to how far apart they are in the Unicode table.
Let’s write a function that takes a number of positions to shift and a string, and returns that string where every character is shifted forward in the alphabet by that many positions.
import Data.Char
encode :: Int -> String -> String
encode offset msg = map (\c -> chr $ ord c + offset) msg
Encoding a string is as simple as taking our message and mapping over it a function that takes a character, converts it to its corresponding number, adds an offset, and then converts it back to a character. A composition cowboy would write this function as (chr . (+ offset) . ord) .
ghci> encode 3 "hey mark"
"kh|#pdun"
ghci> encode 5 "please instruct your men"
"uqjfxj%nsxywzhy%~tzw%rjs"
ghci> encode 1 "to party hard"
"up!qbsuz!ibse"
That’s definitely encoded!
Decoding a message is basically just shifting it back by the number of places it was shifted by in the first place.
decode :: Int -> String -> String
decode shift msg = encode (negate shift) msg
Now we can test it by decoding Caesar’s message:
ghci> decode 3 "kh|#pdun"
"hey mark"
ghci> decode 5 "uqjfxj%nsxywzhy%~tzw%rjs"
"please instruct your men"
ghci> decode 1 "up!qbsuz!ibse"
"to party hard"
On Strict Left Folds
In the previous chapter, you saw how foldl works and how you can use it to implement all sorts of cool functions. However, there’s a catch to foldl that we haven’t yet explored: Using foldl can sometimes lead to so-called stack overflow errors, which occur when your program uses too much space in a specific part of your computer’s memory. To demonstrate, let’s use foldl with the + function to sum a list that consists of a hundred 1 s:
ghci> foldl (+) 0 (replicate 100 1)
100
This seems to work. What if we want to use foldl to sum a list that has, as Dr. Evil would put it, one million 1 s?
ghci> foldl (+) 0 (replicate 1000000 1)
*** Exception: stack overflow
Ooh, that is truly evil! Now why does this happen? Haskell is lazy, and so it defers actual computation of values for as long as possible. When we use foldl , Haskell doesn’t compute (that is, evaluate) the actual accumulator on every step. Instead, it defers its evaluation. In the next step, it again doesn’t evaluate the accumulator, but defers the evaluation. It also keeps the old deferred computation in memory, because the new one often refers to its result. So as the fold merrily goes along its way, it builds up a bunch of deferred computations, each taking a not insignificant amount of memory. Eventually, this can cause a stack overflow error.
Here’s how Haskell evaluates the expression foldl (+) 0 [1,2,3] :
foldl (+) 0 [1,2,3] =
foldl (+) (0 + 1) [2,3] =
foldl (+) ((0 + 1) + 2) [3] =
foldl (+) (((0 + 1) + 2) + 3) [] =
((0 + 1) + 2) + 3 =
(1 + 2) + 3 =
3 + 3 =
6
As you can see, it first builds up a big stack of deferred computations. Then, once it reaches the empty list, it goes about actually evaluating those deferred computations. This isn’t a problem for small lists, but for large lists that contain upward of a million elements, you get a stack overflow, because evaluating all these deferred computations is done recursively. Wouldn’t it be nice if there was a function named, say, foldl' , that didn’t defer computations? It would work like this:
foldl' (+) 0 [1,2,3] =
foldl' (+) 1 [2,3] =
foldl' (+) 3 [3] =
foldl' (+) 6 [] =
6
Computations wouldn’t be deferred between steps of foldl , but would get evaluated immediately. Well, we’re in luck, because Data.List offers this stricter version of foldl , and it is indeed called foldl' . Let’s try to compute the sum of a million 1 s with foldl' :
ghci> foldl' (+) 0 (replicate 1000000 1)
1000000
Great success! So, if you get stack overflow errors when using foldl , try switching to foldl' . There’s also a stricter version of foldl1 , named foldl1' .
Let’s Find Some Cool Numbers
You’re walking along the street, and an old lady comes up to you and says, “Excuse me, what’s the first natural number such that the sum of its digits equals 40?”
Well, what now, hotshot? Let’s use some Haskell magic to find such a number. For instance, if we sum the digits of the number 123, we get 6, because 1 + 2 + 3 equals 6. So, what is the first number that has such a property that its digits add up to 40?
First, let’s make a function that takes a number and tells us the sum of its digits. We’re going to use a cool trick here. First, we’ll convert our number to a string by using the show function. Once we have a string, we’ll turn each character in that string into a number and then just sum that list of numbers. To turn a character into a number, we’ll use a handy function from Data.Char called digitToInt . It takes a Char and returns an Int :
ghci> digitToInt '2'
2
ghci> digitToInt 'F'
15
ghci> digitToInt 'z'
*** Exception: Char.digitToInt: not a digit 'z'
It works on the characters in the range from '0' to '9' and from 'A' to 'F' (they can also be in lowercase).
Here’s our function that takes a number and returns the sum of its digits:
import Data.Char
import Data.List
digitSum :: Int -> Int
digitSum = sum . map digitToInt . show
We convert it to a string, map digitToInt over that string, and then sum the resulting list of numbers.
Now we need to find the first natural number such that when we apply digitSum to it, we get 40 as the result. To do that, we’ll use the find function, which resides in Data.List . It takes a predicate and a list and returns the first element of the list that matches the predicate. However, it has a rather peculiar type declaration:
ghci> :t find
find :: (a -> Bool) -> [a] -> Maybe a
The first parameter is a predicate, and the second parameter is a list—no big deal here. But what about the return value? It says Maybe a . That’s a type you haven’t met before. A value with a type of Maybe a is sort of like a list of type [a] . Whereas a list can have zero, one, or many elements, a Maybe a typed value can have either zero elements or just one element. We use it when we want to represent possible failure. To make a value that holds nothing, we just use Nothing . This is analogous to the empty list. To construct a value that holds something, say the string "hey" , we write Just "hey" . Here’s a quick demonstration:
ghci> Nothing
Nothing
ghci> Just "hey"
Just "hey"
ghci> Just 3
Just 3
ghci> :t Just "hey"
Just "hey" :: Maybe [Char]
ghci> :t Just True
Just True :: Maybe Bool
As you can see, a value of Just True has a type of Maybe Bool , kind of like how a list that holds Booleans would have a type of [Bool] .
If find finds an element that satisfies the predicate, it will return that element wrapped in a Just . If it doesn’t, it will return a Nothing :
ghci> find (> 4) [3,4,5,6,7]
Just 5
ghci> find odd [2,4,6,8,9]
Just 9
ghci> find (=='z') "mjolnir"
Nothing
Now let’s get back to making our function. We have our digitSum function and know how find works, so all that’s left to do is put these two together. Remember that we want to find the first number whose digits add up to 40.
firstTo40 :: Maybe Int
firstTo40 = find (\x -> digitSum x == 40) [1..]
We just take the infinite list [1..] , and then find the first number whose digitSum is 40.
ghci> firstTo40
Just 49999
There’s our answer! If we want to make a more general function that is not fixed on 40 but takes our desired sum as the parameter, we can change it like so:
firstTo :: Int -> Maybe Int
firstTo n = find (\x -> digitSum x == n) [1..]
Here’s a quick test:
ghci> firstTo 27
Just 999
ghci> firstTo 1
Just 1
ghci> firstTo 13
Just 49
Mapping Keys to Values
When dealing with data in some sort of collection, we often don’t care if it’s in some kind of order; we just want to be able to access it by a certain key. For example, if we want to know who lives at a certain address, we want to look up the name based on the address. When doing such things, we say that we looked up our desired value (someone’s name) by some sort of key (that person’s address).
Almost As Good: Association Lists
There are many ways to achieve key/value mappings. One of them is the association list . Association lists (also called dictionaries ) are lists that are used to store key/value pairs where ordering doesn’t matter. For instance, we might use an association list to store phone numbers, where phone numbers would be the values and people’s names would be the keys. We don’t care in which order they’re stored; we just want to get the right phone number for the right person.
The most obvious way to represent association lists in Haskell would be by having a list of pairs. The first component in the pair would be the key, and the second component would be the value. Here’s an example of an association list with phone numbers:
phoneBook =
[("betty", "555-2938")
,("bonnie", "452-2928")
,("patsy", "493-2928")
,("lucille", "205-2928")
,("wendy", "939-8282")
,("penny", "853-2492")
]
Despite this seemingly odd indentation, this is just a list of pairs of strings.
The most common task when dealing with association lists is looking up some value by key. Let’s make a function that looks up some value given a key.
findKey :: (Eq k) => k -> [(k, v)] -> v
findKey key xs = snd . head . filter (\(k, v) -> key == k) $ xs
This is pretty simple. The function takes a key and a list, filters the list so that only matching keys remain, gets the first key/value pair that matches, and returns the value.
But what happens if the key we’re looking for isn’t in the association list? Hmm. Here, if a key isn’t in the association list, we’ll end up trying to get the head of an empty list, which throws a runtime error. We should avoid making our programs so easy to crash, so let’s use the Maybe data type. If we don’t find the key, we’ll return a Nothing . If we find it, we’ll return Just something , where something is the value corresponding to that key.
findKey :: (Eq k) => k -> [(k, v)] -> Maybe v
findKey key [] = Nothing
findKey key ((k,v):xs)
| key == k = Just v
| otherwise = findKey key xs
Look at the type declaration. It takes a key that can be equated and an association list, and then it maybe produces a value. Sounds about right.
This is a textbook recursive function that operates on a list. Base case, splitting a list into a head and a tail, recursive calls—they’re all there. This is the classic fold pattern, so let’s see how this would be implemented as a fold.
findKey :: (Eq k) => k -> [(k, v)] -> Maybe v
findKey key xs = foldr (\(k, v) acc -> if key == k then Just v else acc) Nothing xs
Note
It’s usually better to use folds for this standard list recursion pattern, rather than explicitly writing the recursion, because they’re easier to read and identify. Everyone knows it’s a fold when they see the foldr call, but it takes some more thinking to read explicit recursion.
ghci> findKey "penny" phoneBook
Just "853-2492"
ghci> findKey "betty" phoneBook
Just "555-2938"
ghci> findKey "wilma" phoneBook
Nothing
This works like a charm! If we have the girl’s phone number, we Just get the number; otherwise, we get Nothing .
Enter Data.Map
We just implemented the lookup function from Data.List . If we want the value that corresponds to a key, we need to traverse all the elements of the list until we find it.
It turns out that the Data.Map module offers association lists that are much faster, and it also provides a lot of utility functions. From now on, we’ll say we’re working with maps instead of association lists.
Because Data.Map exports functions that clash with the Prelude and Data.List ones, we’ll do a qualified import.
import qualified Data.Map as Map
Put this import statement into a script, and then load the script via GHCi.
We’re going to turn an association list into a map by using the fromList function from Data.Map . fromList takes an association list (in the form of a list) and returns a map with the same associations. Let’s play around a bit with fromList first:
ghci> Map.fromList [(3,"shoes"),(4,"trees"),(9,"bees")]
fromList [(3,"shoes"),(4,"trees"),(9,"bees")]
ghci> Map.fromList [("kima","greggs"),("jimmy","mcnulty"),("jay","landsman")]
fromList [("jay","landsman"),("jimmy","mcnulty"),("kima","greggs")]
When a map from Data.Map is displayed on the terminal, it’s shown as fromList and then an association list that represents the map, even though it’s not a list anymore.
If there are duplicate keys in the original association list, the duplicates are just discarded:
ghci> Map.fromList [("MS",1),("MS",2),("MS",3)]
fromList [("MS",3)]
This is the type signature of fromList :
Map.fromList :: (Ord k) => [(k, v)] -> Map.Map k v
It says that it takes a list of pairs of type k and v , and returns a map that maps from keys of type k to values of type v . Notice that when we were doing association lists with normal lists, the keys only needed to be equatable (their type belonging to the Eq type class), but now they must be orderable. That’s an essential constraint in the Data.Map module. It needs the keys to be orderable so it can arrange and access them more efficiently.
Now we can modify our original phoneBook association list to be a map. We’ll also add a type declaration, just because we can:
import qualified Data.Map as Map
phoneBook :: Map.Map String String
phoneBook = Map.fromList $
[("betty", "555-2938")
,("bonnie", "452-2928")
,("patsy", "493-2928")
,("lucille", "205-2928")
,("wendy", "939-8282")
,("penny", "853-2492")
]
Cool! Let’s load this script into GHCi and play around with our phoneBook . First, we’ll use lookup to search for some phone numbers. lookup takes a key and a map, and tries to find the corresponding value in the map. If it succeeds, it returns the value wrapped in a Just ; otherwise, it returns a Nothing :
ghci> :t Map.lookup
Map.lookup :: (Ord k) => k -> Map.Map k a -> Maybe a
ghci> Map.lookup "betty" phoneBook
Just "555-2938"
ghci> Map.lookup "wendy" phoneBook
Just "939-8282"
ghci> Map.lookup "grace" phoneBook
Nothing
For our next trick, we’ll make a new map from phoneBook by inserting a number. insert takes a key, a value, and a map, and returns a new map that’s just like the old one, but with the key and value inserted:
ghci> :t Map.insert
Map.insert :: (Ord k) => k -> a -> Map.Map k a -> Map.Map k a
ghci> Map.lookup "grace" phoneBook
Nothing
ghci> let newBook = Map.insert "grace" "341-9021" phoneBook
ghci> Map.lookup "grace" newBook
Just "341-9021"
Let’s check how many numbers we have. We’ll use the size function from Data.Map , which takes a map and returns its size. This is pretty straightforward:
ghci> :t Map.size
Map.size :: Map.Map k a -> Int
ghci> Map.size phoneBook
6
ghci> Map.size newBook
7
The numbers in our phone book are represented as strings. Suppose we would rather use lists of Int s to represent phone numbers. So, instead of having a number like "939-8282" , we want to have [9,3,9,8,2,8,2] . First, we’re going to make a function that converts a phone number string to a list of Int s. We can try to map digitToInt from Data.Char over our string, but it won’t know what to do with the dash! That’s why we need to get rid of anything in that string that isn’t a number. To do this, we’ll seek help from the isDigit function from Data.Char , which takes a character and tells us if it represents a digit. Once we’ve filtered our string, we’ll just map digitToInt over it.
string2digits :: String -> [Int]
string2digits = map digitToInt . filter isDigit
Oh, be sure to import Data.Char , if you haven’t already.
Let’s try this out:
ghci> string2digits "948-9282"
[9,4,8,9,2,8,2]
Very cool! Now, let’s use the map function from Data.Map to map string2digits over our phoneBook :
ghci> let intBook = Map.map string2digits phoneBook
ghci> :t intBook
intBook :: Map.Map String [Int]
ghci> Map.lookup "betty" intBook
Just [5,5,5,2,9,3,8]
The map from Data.Map takes a function and a map, and applies that function to each value in the map.
Let’s extend our phone book. Say that a person can have several numbers, and we have an association list set up like this:
phoneBook =
[("betty", "555-2938")
,("betty", "342-2492")
,("bonnie", "452-2928")
,("patsy", "493-2928")
,("patsy", "943-2929")
,("patsy", "827-9162")
,("lucille", "205-2928")
,("wendy", "939-8282")
,("penny", "853-2492")
,("penny", "555-2111")
]
If we just use fromList to put that into a map, we’ll lose a few numbers! Instead, we’ll use another function found in Data.Map : fromListWith . This function acts like fromList , but instead of discarding duplicate keys, it uses a function supplied to it to decide what to do with them.
phoneBookToMap :: (Ord k) => [(k, String)] -> Map.Map k String
phoneBookToMap xs = Map.fromListWith add xs
where add number1 number2 = number1 ++ ", " ++ number2
If fromListWith finds that the key is already there, it uses the function supplied to it to join those two values into one and replaces the old value with the one it got by passing the conflicting values to the function:
ghci> Map.lookup "patsy" $ phoneBookToMap phoneBook
Just "827-9162, 943-2929, 493-2928"
ghci> Map.lookup "wendy" $ phoneBookToMap phoneBook
Just "939-8282"
ghci> Map.lookup "betty" $ phoneBookToMap phoneBook
Just "342-2492, 555-2938"
We could also first make all the values in the association list singleton lists and then use ++ to combine the numbers:
phoneBookToMap :: (Ord k) => [(k, a)] -> Map.Map k [a]
phoneBookToMap xs = Map.fromListWith (++) $ map (\(k, v) -> (k, [v])) xs
Let’s test this in GHCi:
ghci> Map.lookup "patsy" $ phoneBookToMap phoneBook
Just ["827-9162","943-2929","493-2928"]
Pretty neat!
Now suppose we’re making a map from an association list of numbers, and when a duplicate key is found, we want the biggest value for the key to be kept. We can do that like so:
ghci> Map.fromListWith max [(2,3),(2,5),(2,100),(3,29),(3,22),(3,11),(4,22),(4,15)]
fromList [(2,100),(3,29),(4,22)]
Or we could choose to add together values that share keys:
ghci> Map.fromListWith (+) [(2,3),(2,5),(2,100),(3,29),(3,22),(3,11),(4,22),(4,15)]
fromList [(2,108),(3,62),(4,37)]
So, you’ve seen that Data.Map and the other modules provided by Haskell are pretty cool. Next, we’ll look at how to make your own module.
Making Our Own Modules
As I said at the beginning of this chapter, when you’re writing programs, it’s good practice to take functions and types that work toward a similar purpose and put them in a separate module. That way, you can easily reuse those functions in other programs by just importing your module.
We say that a module exports functions. When you import a module, you can use the functions that it exports. A module can also define functions that it uses internally, but we can see and use only the ones that it exports.
A Geometry Module
To demonstrate, we’ll create a little module that provides some functions for calculating the volume and area of a few geometrical objects. We’ll start by creating a file called Geometry.hs .
At the beginning of a module, we specify the module name. If we have a file called Geometry.hs , then we should name our module Geometry . We specify the functions that it exports, and then we can add the functions. So we’ll start with this:
module Geometry
( sphereVolume
, sphereArea
, cubeVolume
, cubeArea
, cuboidArea
, cuboidVolume
) where
As you can see, we’ll be doing areas and volumes for spheres, cubes, and cuboids. A sphere is a round thing like a grapefruit, a cube is like a game die, and a (rectangular) cuboid is like a box of cigarettes. (Kids, don’t smoke!)
Now let’s define our functions:
module Geometry
( sphereVolume
, sphereArea
, cubeVolume
, cubeArea
, cuboidArea
, cuboidVolume
) where
sphereVolume :: Float -> Float
sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3)
sphereArea :: Float -> Float
sphereArea radius = 4 * pi * (radius ^ 2)
cubeVolume :: Float -> Float
cubeVolume side = cuboidVolume side side side
cubeArea :: Float -> Float
cubeArea side = cuboidArea side side side
cuboidVolume :: Float -> Float -> Float -> Float
cuboidVolume a b c = rectArea a b * c
cuboidArea :: Float -> Float -> Float -> Float
cuboidArea a b c = rectArea a b * 2 + rectArea a c * 2 +
rectArea c b * 2
rectArea :: Float -> Float -> Float
rectArea a b = a * b
This is pretty standard geometry, but there are a few items to note. One is that because a cube is only a special case of a cuboid, we define its area and volume by treating it as a cuboid whose sides are all of the same length. We also define a helper function called rectArea , which calculates a rectangle’s area based on the lengths of its sides. It’s rather trivial because it’s just multiplication. Notice that we used it in our functions in the module (in cuboidArea and cuboidVolume ), but we didn’t export it! This is because we want our module to present just functions for dealing with three-dimensional objects.
When making a module, we usually export only those functions that act as a sort of interface to our module so that the implementation is hidden. People who use our Geometry module don’t need to concern themselves with functions that we don’t export. We can decide to change those functions completely or delete them in a newer version (we could delete rectArea and just use * instead), and no one will mind, because we didn’t export them in the first place.
To use our module, we just do this:
import Geometry
However, Geometry.hs must be in the same folder as the module that’s importing it.
Hierarchical Modules
Modules can also be given a hierarchical structure. Each module can have a number of submodules, which can have submodules of their own. Let’s section our geometry functions so that Geometry is a module that has three submodules: one for each type of object.
First, we’ll make a folder called Geometry . In it, we’ll place three files: Sphere.hs , Cuboid.hs , and Cube.hs . Let’s look at what each of the files contains.
Here are the contents of Sphere.hs :
module Geometry.Sphere
( volume
, area
) where
volume :: Float -> Float
volume radius = (4.0 / 3.0) * pi * (radius ^ 3)
area :: Float -> Float
area radius = 4 * pi * (radius ^ 2)
The Cuboid.hs file looks like this:
module Geometry.Cuboid
( volume
, area
) where
volume :: Float -> Float -> Float -> Float
volume a b c = rectArea a b * c
area :: Float -> Float -> Float -> Float
area a b c = rectArea a b * 2 + rectArea a c * 2 + rectArea c b * 2
rectArea :: Float -> Float -> Float
rectArea a b = a * b
And our last file, Cube.hs , has these contents:
module Geometry.Cube
( volume
, area
) where
import qualified Geometry.Cuboid as Cuboid
volume :: Float -> Float
volume side = Cuboid.volume side side side
area :: Float -> Float
area side = Cuboid.area side side side
Notice how we placed Sphere.hs in a folder called Geometry , and then defined the module name as Geometry.Sphere . We did the same for the cube and cuboid objects. Also notice how in all three sub-modules, we defined functions with the same names. We can do this because they’re in separate modules.
So, now we can do this:
import Geometry.Sphere
And then we can call area and volume , and they’ll give us the area and volume for a sphere.
If we want to juggle two or more of these modules, we need to do qualified imports because they export functions with the same names. Here’s an example:
import qualified Geometry.Sphere as Sphere
import qualified Geometry.Cuboid as Cuboid
import qualified Geometry.Cube as Cube
And then we can call Sphere.area , Sphere.volume , Cuboid.area , and so on, and each will calculate the area or volume for its corresponding object.
The next time you find yourself writing a file that’s really big and has a lot of functions, look for functions that serve some common purpose and consider putting them in their own module. Then you’ll be able to just import your module the next time you’re writing a program that requires some of the same functionality.