Composition & pipelines in Haskell
Counts words two ways, putting point-free and pointed style side by side.
-- (.) glues functions right to left; ($) applies one without parens.
module WordStats where
import Data.Char (isAlpha, toLower)
normalize :: String -> String
normalize = map toLower . filter (\c -> isAlpha c || c == ' ')
-- Point-free: the text argument is never named at all.
wordCount :: String -> Int
wordCount = length . words . normalize
-- The same pipeline written pointed, with ($) in place of nesting.
wordCountPointed :: String -> Int
wordCountPointed text = length $ words $ normalize text
longest :: String -> Int
longest = maximum . (0 :) . map length . words . normalize
How it works
normalizecomposesmap toLowerwith afilterthat drops punctuation.wordCount = length . words . normalizenever names its argument at all.wordCountPointed text = length $ words $ normalize textdoes the same job with($).
Keywords and builtins used here
IntStringimportisAlphalongestmodulenormalizetoLowerwherewordCountwordCountPointed
The run, in numbers
- Lines
- 18
- Characters to type
- 590
- Tokens
- 81
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 69 seconds.
Step 3 of 3 in Functions, step 6 of 27 in Language basics.