Skip to content
Lists
step 1/5

Reading — step 1 of 5

Learn

~1 min readLists and Beyond

Lists are linked lists of homogeneous values:

nums :: [Int]
nums = [1, 2, 3, 4, 5]

-- Constructors:
-- []     -- empty
-- x : xs -- cons (prepend x to xs)
[1, 2, 3] == 1 : 2 : 3 : []   -- True

Common operations:

length [1,2,3]      -- 3
head [1,2,3]        -- 1 (errors on [])
tail [1,2,3]        -- [2,3]
last [1,2,3]        -- 3
take 2 [1,2,3]      -- [1, 2]
drop 2 [1,2,3]      -- [3]
reverse [1,2,3]    -- [3,2,1]
[1,2] ++ [3,4]      -- [1,2,3,4]

List comprehensions (set-builder syntax):

[x * x | x <- [1..10], x `mod` 2 == 0]   -- [4, 16, 36, 64, 100]

Lazy evaluation lets you use infinite lists: take 5 [1..] = [1,2,3,4,5].

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…