Haskell Cheatsheet
Prelude Quick Reference
Use this Haskell reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Numeric Helpers
abs (-3) -- 3 signum (-3) -- -1 min 2 5 -- 2 max 2 5 -- 5 div 10 3 -- 3 mod 10 3 -- 1 10 `quot` 3 -- 3 10 `rem` 3 -- 1 gcd 12 18 -- 6 2 ^ 10 -- 1024 (integer power), 2 ** 0.5 for floating
div/mod round toward negative infinity, quot/rem truncate toward zero.
Core Combinators
id 5 -- 5 const 1 "ignored" -- 1 flip (-) 1 10 -- 9, flips argument order uncurry (+) (2, 3) -- 5, tuple in, function of two args curry fst 1 2 -- 1, the reverse fst (1, 'a') -- 1 snd (1, 'a') -- 'a'
flip, const, and uncurry show up constantly with map, foldr, and zipWith.
Words, Lines, Show, Read
words "a b c" -- ["a","b","c"] unwords ["a","b","c"] -- "a b c" lines "one\ntwo" -- ["one","two"] unlines ["one","two"] -- "one\ntwo\n" show 42 -- "42" read "42" :: Int -- 42, partial: crashes on bad input readMaybe "42" :: Maybe Int -- Just 42 (Text.Read)
show and read round-trip for derived instances. Parse untrusted input with readMaybe.
Generating Lists
replicate 3 'x' -- "xxx" take 5 (iterate (*2) 1) -- [1,2,4,8,16] take 3 (repeat 0) -- [0,0,0] take 5 (cycle [1,2]) -- [1,2,1,2,1] zip [0..] "abc" -- [(0,'a'),(1,'b'),(2,'c')], index anything
iterate, repeat, and cycle build infinite lists. Laziness makes that fine as long as you take.
Folds
foldr (\x acc -> x : acc) [] [1,2,3] -- [1,2,3], rebuilds the list foldr (&&) True [True, False] -- False, lazy so it can stop early foldl' (+) 0 [1..1000000] -- 500000500000, strict (Data.List) foldl' max 0 [3,1,4,1,5] -- 5 sum, product, maximum, minimum -- fold shorthands (last two are partial)
Maybe Utilities
maybe "fallback" show (Just 3) -- "3" maybe "fallback" show Nothing -- "fallback" fromMaybe 0 (Just 3) -- 3 catMaybes [Just 1, Nothing, Just 2] -- [1,2] mapMaybe (\s -> readMaybe s :: Maybe Int) ["1","x","2"] -- [1,2]
fromMaybe, catMaybes, mapMaybe, isJust, isNothing, and listToMaybe come from Data.Maybe.
Either Utilities
either length show (Left "err") -- 3 either length show (Right 42) -- "42"
Use Either e a when failure should carry information. From Data.Either: lefts, rights, partitionEithers, fromRight.
Debugging in GHCi
:type map :info Maybe :load Main.hs :reload :set +t
In source code, Debug.Trace.trace can print while evaluating, but remove it from production code.