typestar

Building lists in Haskell

(:) adds one element to the front, (++) joins two whole lists, and a pattern covers the empty case.

-- (:) prepends one element; (++) joins two whole lists end to end
markers :: [String]
markers = "trailhead" : ("cairn" : ["footbridge"]) ++ ["summit"]

-- head and tail would grab the ends, but they crash on an empty list,
-- and GHC now rejects both under -Wall; match the two cases instead
firstMarker :: [String] -> String
firstMarker [] = "no markers logged yet"
firstMarker (m : _) = m

-- matching (m : rest) names the head and the rest in one pattern
describe :: [String] -> String
describe [] = "nothing to walk yet"
describe (m : rest) = m ++ ", then " ++ show (length rest) ++ " more"

main :: IO ()
main = do
  putStrLn (describe markers)
  putStrLn (firstMarker markers ++ " -> " ++ unwords (drop 1 markers))
  print (null markers, length markers)

How it works

  1. markers chains three names with (:) and then glues ["summit"] onto the end with (++).
  2. firstMarker matches [] and (m : _) rather than calling head, which crashes on an empty list.
  3. describe names both halves at once with (m : rest), and main reports null markers and length markers.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
754
Tokens
124
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 1 of 3 in Lists, step 10 of 27 in Language basics.

← Previous Next →

Building lists in other languages