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
markerschains three names with(:)and then glues["summit"]onto the end with(++).firstMarkermatches[]and(m : _)rather than callinghead, which crashes on an empty list.describenames both halves at once with(m : rest), andmainreportsnull markersandlength markers.
Keywords and builtins used here
IOString_describedofirstMarkermainmarkers
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.
Step 1 of 3 in Lists, step 10 of 27 in Language basics.