typestar

Tuples and pairs in Haskell

Pairs seat rows with ticket counts, then picks out the busiest row.

-- A tuple pattern takes a pair apart in one step.
module SeatChart where

rows :: [String]
rows = ["A", "B", "C"]

-- zip pairs the lists element by element, stopping at the shorter.
chart :: [(String, Int)]
chart = zip rows [12, 4, 9]

totalSold :: Int
totalSold = sum (map snd chart)

-- The lambda matches its pair instead of reaching for fst and snd.
busiest :: (Int, String)
busiest = maximum (map (\(row, n) -> (n, row)) chart)

banner :: String
banner = bestRow ++ ": " ++ show bestCount ++ " of " ++ show totalSold
  where (bestCount, bestRow) = busiest

How it works

  1. zip rows [12, 4, 9] builds a list of (String, Int) pairs from two lists.
  2. map snd chart pulls out the counts, while the lambda \(row, n) -> (n, row) flips each pair.
  3. where (bestCount, bestRow) = busiest destructures the winner into two names.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
560
Tokens
113
Three-star pace
75 tpm

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

Type this snippet

Step 3 of 3 in Pattern matching, step 9 of 27 in Language basics.

← Previous Next →