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
ripeWeightsdraws fromw <- [4, 9, 12, 3, 15]and keeps only the elements passing thew >= 9guard.toOuncesuses its own argument as the generator and divides each element by 28 on the left of the bar.plotLabelsruns two generators,row <- "ABC"andbed <- [1 .. 3 :: Int], andneighborPairsbuilds(a, b)tuples while itsa /= bguard skips self-pairs.
Keywords and builtins used here
IntStringmoduleneighborPairsplotLabelsripeWeightstoOunceswhere
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.
Step 3 of 3 in Lists, step 12 of 27 in Language basics.