List Functions
Prerequisites: Lists
The Prelude — the module every Haskell file imports automatically —
includes dozens of list functions. These cover most everyday needs:
main :: IO ()
main = do
let xs = [5, 3, 8, 1, 9, 2] :: [Int]
print (take 3 xs, drop 3 xs)
print (splitAt 2 xs)
print (sum xs, product xs, maximum xs, minimum xs)
print (elem 8 xs, 8 `elem` xs, notElem 7 xs)
print (takeWhile (> 2) xs, dropWhile (> 2) xs)
print (span even [2, 4, 5, 6])
print (replicate 3 'x', concat [[1, 2], [3], [4, 5]])
print (and [True, False], or [True, False])
print (any even xs, all (> 0) xs)
([5,3,8],[1,9,2])
([5,3],[8,1,9,2])
(28,2160,9,1)
(True,True,True)
([5,3,8],[1,9,2])
([2,4],[5,6])
("xxx",[1,2,3,4,5])
(False,True)
(True,True)
map and filter
map applies a function to every element; filter keeps the elements
for which a function returns True:
import Data.Char (toUpper)
main :: IO ()
main = do
print (map (* 3) [1, 2, 3])
print (map toUpper "shout")
print (filter odd [1 .. 10])
print (map length (words "the quick brown fox"))
[3,6,9]
"SHOUT"
[1,3,5,7,9]
[3,5,5,3]
zip and friends
main :: IO ()
main = do
print (zip [1, 2, 3] "abc")
print (zip [1 ..] ["gold", "silver", "bronze"])
print (zipWith (+) [1, 2, 3] [10, 20, 30])
print (unzip [(1, 'a'), (2, 'b')])
print (lookup 2 [(1, "one"), (2, "two")])
[(1,'a'),(2,'b'),(3,'c')]
[(1,"gold"),(2,"silver"),(3,"bronze")]
[11,22,33]
([1,2],"ab")
Just "two"
zip stops at the shorter list, which is why pairing with the infinite
list [1 ..] is a common way to number things. lookup searches a list
of pairs and returns a Maybe (Just a value or Nothing).
Data.List
More functions live in Data.List:
import Data.List (sort, sortOn, nub, group, intercalate, isPrefixOf, partition)
main :: IO ()
main = do
print (sort [3, 1, 2])
print (sortOn negate [3, 1, 2])
print (nub [1, 1, 2, 3, 2])
print (map length (group (sort "mississippi")))
putStrLn (intercalate ", " ["a", "b", "c"])
print ("has" `isPrefixOf` "haskell")
print (partition even [1 .. 10])
[1,2,3]
[3,2,1]
[1,2,3]
[4,1,2,4]
a, b, c
True
([2,4,6,8,10],[1,3,5,7,9])
import Data.List (sort, ...) imports just the names you list — a good
habit that shows where each function comes from.
Practice
Given scores = [72, 95, 58, 88, 61], print how many scores are 60 or
higher, and the top three scores in descending order.
Show solution
import Data.List (sortOn)
main :: IO ()
main = do
let scores = [72, 95, 58, 88, 61] :: [Int]
print (length (filter (>= 60) scores))
print (take 3 (sortOn negate scores))
4
[95,88,72]