Haskell Cheatsheet

Functions

Use this Haskell reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Function Definition

add :: Int -> Int -> Int
add x y = x + y

isEven :: Int -> Bool
isEven n = n `mod` 2 == 0

Function application uses spaces, not parentheses: add 2 3.

Currying and Partial Application

add :: Int -> Int -> Int
add x y = x + y

add10 :: Int -> Int
add10 = add 10

halve :: Double -> Double
halve = (/ 2)

Every multi-argument function can be partially applied.

Lambdas

map (\x -> x * x) [1,2,3]     -- [1,4,9]
filter (\n -> n > 3) [1..10]  -- [4,5,6,7,8,9,10]

zipWith (\a b -> (a, b * 2)) [1,2] [10,20]  -- [(1,20),(2,40)]

With LambdaCase (on by default in GHC2024, otherwise {-# LANGUAGE LambdaCase #-}), \case pattern matches directly on the argument:

classify = \case
  0 -> "zero"
  n | n > 0     -> "positive"
    | otherwise -> "negative"

Operator Sections

map (* 2) [1,2,3]     -- [2,4,6]
map (2 ^) [1,2,3]     -- [2,4,8]   left section: 2 ^ x
map (^ 2) [1,2,3]     -- [1,4,9]   right section: x ^ 2
filter (> 3) [1..6]   -- [4,5,6]
map (subtract 1) [5]  -- [4]  ((- 1) is the literal negative one, not a section)

Composition and Application

result = length (filter even [1..20])

same = length $ filter even [1..20]

pipeline = sum . map (^2) . filter odd
-- pipeline [1..5] == 35
  • ($) lowers parentheses: f $ g x means f (g x).
  • (.) composes functions: (f . g) x means f (g x), right to left.

For left-to-right pipelines use (&) from Data.Function:

import Data.Function ((&))

[1..20] & filter even & map (^2) & sum  -- 1540

Guards

grade :: Int -> String
grade score
  | score >= 90 = "A"
  | score >= 80 = "B"
  | score >= 70 = "C"
  | otherwise   = "D"

Guards are ideal when branches depend on boolean conditions. otherwise is just True.