typestar

List comprehensions in Haskell

Generators on the right of the bar feed the expression on the left, and guards drop what fails.

module Comprehensions where

-- a generator on the left of the bar, a guard on the right to filter
ripeWeights :: [Int]
ripeWeights = [w | w <- [4, 9, 12, 3, 15], w >= 9]

-- the head of the comprehension transforms each element it draws
toOunces :: [Int] -> [Int]
toOunces ws = [w `div` 28 | w <- ws]

-- two generators nest, and the rightmost one changes fastest
plotLabels :: [String]
plotLabels = [row : show bed | row <- "ABC", bed <- [1 .. 3 :: Int]]

-- the head can build pairs; the guard skips a plot paired with itself
neighborPairs :: [(Int, Int)]
neighborPairs = [(a, b) | a <- [1 .. 3], b <- [1 .. 3], a /= b]

How it works

  1. ripeWeights draws from w <- [4, 9, 12, 3, 15] and keeps only the elements passing the w >= 9 guard.
  2. toOunces uses its own argument as the generator and divides each element by 28 on the left of the bar.
  3. plotLabels runs two generators, row <- "ABC" and bed <- [1 .. 3 :: Int], and neighborPairs builds (a, b) tuples while its a /= b guard skips self-pairs.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
622
Tokens
125
Three-star pace
70 tpm

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

Type this snippet

Step 3 of 3 in Lists, step 12 of 27 in Language basics.

← Previous Next →

List comprehensions in other languages