Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 57 ยท Practice and interviews

Haskell Cheat Sheet

A compact Haskell cheat sheet: syntax, Prelude functions, type classes, monad idioms, GHCi commands and common GHC extensions, with links to each lesson.

This is a quick reference for everything you have learned in the Haskell course. It is meant to be scanned, not read in order: pick the section you need and follow the links when a topic needs more than a one-liner. All Haskell blocks are read-only. The runnable examples at the end are JavaScript stand-ins for the idioms that matter most.

Names in backticks are real Prelude or base functions unless a line says otherwise.

The whole language, briefly

Types Int, Integer, Double, Bool, Char, String.
Data data, newtype, type, records.
Classes Eq, Ord, Show, Functor, Monad.
Tools GHCi, Cabal, Stack, HLint.
1 / 2

Syntax at a glance

HASKELL
-- line comment
 block comment 

module Main (main) where          -- header and exports
import Data.List (sort, foldl')   -- selective import
import qualified Data.Map as Map  -- qualified import

x :: Int                          -- signature
x = 42

square :: Int -> Int
square n = n * n

add :: Int -> Int -> Int          -- curried
add a b = a + b

fact :: Integer -> Integer        -- pattern matching
fact 0 = 1
fact n = n * fact (n - 1)

classify :: Int -> String         -- guards
classify n
  | n < 0     = "negative"
  | n == 0    = "zero"
  | otherwise = "positive"

area r = pi * r2                  -- where
  where r2 = r * r

let y = 5 in y + 1                -- let expression
if c then a else b                -- both branches required
case m of                         -- case expression
  Just v  -> v
  Nothing -> 0
\a b -> a + b                     -- lambda

Layout rule: items of one block start in the same column. Use spaces, not tabs. More on expressions, pattern matching and guards, where and let.

Types and data declarations

HASKELL
data Shape = Circle Double | Rect Double Double
  deriving (Show, Eq)

data Person = Person
  { name :: String
  , age  :: Int
  } deriving (Show, Eq, Ord)

newtype Meters = Meters Double        -- one constructor, one field
type Name = String                    -- alias

data Tree a = Leaf | Node (Tree a) a (Tree a)   -- recursive, polymorphic

p { age = 31 }                        -- record update (returns a copy)
Type Meaning
Int Fixed-size integer
Integer Arbitrary-size integer
Double Floating point
Bool True or False
Char One Unicode character, 'a'
String [Char], "text"
[a] List of a
(a, b) Pair
Maybe a Nothing or Just a
Either e a Left e or Right a
IO a An action producing a

See basic types, algebraic data types and records and newtype.

Prelude favourites

Function Type (simplified) Example result
map (a -> b) -> [a] -> [b] map (+1) [1,2,3] is [2,3,4]
filter (a -> Bool) -> [a] -> [a] filter even [1..6] is [2,4,6]
foldr (a -> b -> b) -> b -> [a] -> b foldr (+) 0 [1,2,3] is 6
foldl' (b -> a -> b) -> b -> [a] -> b strict left fold
zip [a] -> [b] -> [(a,b)] zip [1,2] "ab" is [(1,'a'),(2,'b')]
zipWith (a->b->c) -> [a] -> [b] -> [c] zipWith (+) [1,2] [10,20] is [11,22]
take, drop Int -> [a] -> [a] take 2 [1,2,3] is [1,2]
takeWhile (a -> Bool) -> [a] -> [a] stop at first failure
length, sum, product on lists sum [1..4] is 10
concat, concatMap flatten concat [[1],[2,3]] is [1,2,3]
reverse, elem elem 3 [1,2,3] is True
lines, words, unwords text splitting words "a b" is ["a","b"]
show, read to and from String show 12 is "12"
fst, snd pair parts fst (1,2) is 1
iterate, repeat, cycle infinite lists use with take
maybe, either consume Maybe, Either
div, mod, quot, rem integer division 7 `div` 2 is 3
fromIntegral integral to any number for Int to Double

head, tail, last, init, !! and fromJust (from Data.Maybe) are partial: avoid them in code that must not crash. See tuples and lists, list comprehensions and higher-order functions.

Operators worth memorizing

Operator Meaning
f $ x f x, lowest precedence
f . g composition: \x -> f (g x)
x : xs cons
xs ++ ys concatenate lists
a <> b semigroup combine
f <$> m fmap f m
mf <*> m applicative apply
m >>= f monadic bind
m >> n run m, discard result, run n
x ``op`` y use a named function infix, for example 10 `mod` 3
(+ 1), (1 +) operator sections

See currying and lambdas and composition.

Type classes

Class Key methods Typical use
Eq ==, /= equality
Ord compare, <, max ordering and sorting
Show / Read show / read text conversion
Enum, Bounded succ, [a ..], minBound ranges
Num +, *, fromInteger numbers
Integral, Fractional div, / whole and fractional numbers
Semigroup, Monoid <>, mempty combining values
Functor fmap map inside a container
Applicative pure, <*> independent effects
Monad >>= dependent steps
Foldable foldr, foldMap reduce a container
Traversable traverse map with effects

Defining your own:

HASKELL
class Describable a where
  describe :: a -> String
  describe _ = "thing"          -- default method

instance Describable Bool where
  describe True  = "yes"
  describe False = "no"

Details in type classes, custom classes, functors, applicatives, monads and monoids.

Monad idioms

HASKELL
-- do notation
main :: IO ()
main = do
  putStrLn "Name?"
  n <- getLine
  let greeting = "Hi, " ++ n
  putStrLn greeting

-- Maybe chaining
f = do
  a <- lookup 1 table
  b <- lookup a table
  pure (a + b)

-- applicative style
Person <$> parseName s <*> parseAge t

mapM_ print [1, 2, 3]         -- run an action for each, ignore results
traverse parse ["1", "2"]     -- collect results, stop on first failure
sequence [Just 1, Just 2]     -- Just [1,2]
when ok (putStrLn "done")     -- from Control.Monad
forM_ [1..3] $ \i -> print i

Remember that return is just pure in a monad. It does not exit a function. See do-notation, Foldable and Traversable and IO basics.

GHCi commands

Command What it does
:load File.hs or :l Load a file
:reload or :r Reload after editing
:type expr or :t Show the type
:info Name or :i Show class, type or function details and instances
:kind T or :k Show the kind of a type
:browse Module List exports
:set -XExtension Enable an extension
:set -Wall Enable warnings
:doc name Show documentation (if available)
:quit or :q Leave

Run a script without compiling with runghc Main.hs, compile with ghc -O2 Main.hs. See GHCi.

Common GHC extensions

Extension Effect
LambdaCase \case Just x -> x; Nothing -> 0
TupleSections (,True)
RecordWildCards Person{..} brings all fields into scope
OverloadedStrings string literals can be Text
ScopedTypeVariables type variables from a signature visible in the body
TypeApplications read @Int "5"
BangPatterns go !acc (x:xs) forces acc
DerivingStrategies, DeriveFunctor... richer deriving
GADTs, DataKinds, TypeFamilies advanced type-level programming

Enable one with # LANGUAGE LambdaCase # at the top of the file or default-extensions in the .cabal file. See GHC extensions and GADTs and type families.

Project and tooling

  • cabal init, cabal build, cabal run, cabal test: the standard workflow (Cabal and Stack).
  • stack new, stack build, stack test: curated snapshots.
  • Compile with -Wall; run HLint for style hints (debugging and profiling).
  • Test with HUnit, Hspec and QuickCheck (testing).
  • Prefer Data.Map.Strict, Data.Text and Data.Vector over lists when data gets large (libraries).

Runnable stand-ins

These JavaScript examples mirror two idioms from the sheet: composing a pipeline and chaining Maybe.

JS Pipeline and sections (JS stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Maybe chaining (JS stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real Haskell gives bind for every monad as >>= and lets you write the chain with do. These stand-ins only cover Maybe.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which GHCi command shows the type of an expression?

    :t (or :type) prints the type. :i shows information, :k shows a kind and :r reloads.
  2. 2. What does f <$> m mean?

    <$> is the infix form of fmap, applying f inside the context m.
  3. 3. Which of these is safe, that is, defined for every input of its type?

    map works on any list, including the empty one. The other three can fail at run time.
  4. 4. Which extension lets you write read @Int "5"?

    TypeApplications allows explicit type arguments with @.

Summary

  • Syntax: signatures, pattern matching, guards, where, let, case, lambdas and the layout rule.
  • Prelude: map, filter, folds, zip and friends; avoid partial functions.
  • Classes: Eq, Ord, Show, Num, then Functor, Applicative, Monad, Monoid, Foldable, Traversable.
  • Monad idioms: do, <$>, <*>, traverse, mapM_, when.
  • GHCi: :t, :i, :l, :r; extensions are enabled with LANGUAGE pragmas.

You have reached the end of the Haskell course. Revisit the introduction or try the practice lessons (functions, lists and recursion) to keep sharpening your skills.