Structure

function :: type -> type
function x = expr
 
function2 :: type -> [type] -> type
function2 x xs = expr
 
main = do
  action
  ...

Function Application

f x y           (f x) y          ((f) (x)) (y)
f x y z         ((f x) y) z      (f x y) z
f $ g x         f (g x)          f . g $ x
f $ g $ h x     f (g (h x))      f . g . h $ x
f $ g x y       f (g x y)        f . g x $ y
f g $ h x       f g (h x)        f g . h $ x

Values and Types

ItemExampleType
booleanTrue | FalseBool
character'a'Char
fixed-precision integer1Int
integer (arbitrary sz.)31337Integer
31337^10Integer
single precision float1.2Float
double precision float1.2Double
list[][a]
[1,2,3][Integer]
['a','b','c'][Char]
"abc"[Char]
[[1,2],[3,4]][[Integer]]
string"asdf"String
tuple(1,2)(Int,Int)
([1,2],'a')([Int],Char)
ordering relationLT, EQ, GTOrdering
function (λ)\x -> ea -> b
maybe (just somethingJust 10Maybe Int
or nothing)NothingMaybe a

Values and Typeclasses

ItemExampleType
Numeric (+,-,*)137Num a => a
Fractional (/)1.2Fractional a => a
Floating1.2Floating a => a
Equatable (==)'a'Eq a => a
Ordered (,>=,>,<)731Ord a => a

Declaring Types and Classes

Type Synonym

type MyType = Type
type PairList a b = [(a,b)]
type String = [Char] -- from Prelude

Data (single constructor)

data MyData = MyData Type Type
  deriving (Class, Class)

Data (multi constructor)

data MyData = Simple Type
            | Duple Type Type
            | Nople

Data (record syntax)

data MDt = MDt { fieldA :: TyAB
               , fieldB :: TyAB
               , fieldC :: TyC }

Newtype

newtype MyType = MyType Type
  deriving (Class, Class)

Typeclass

class MyClass a where
  foo :: a -> a -> b
  goo :: a -> a

Typeclass instance

instance MyClass MyType where
  foo x y = ...
  goo x = ...

Operators (grouped by precedence)

OperatorDescription
!!, .List index, function composition
^, ^^, **raise to: Non-neg. Int, Int, Float
*, /multiplication, fractional division
div, modintegral division (⇒ −∞), modulus
quot, remintegral quotient (⇒ 0), remainder
+, -addition, subtraction
:, ++list construction, append lists
\\list difference
>, >=, <, <=, ==, /=comparisons
elem, notElemlist membership
&&boolean and
|boolean or
>>=, >>sequencing: bind and then
$, $!, seqapplication, strict apl., sequencing

NOTE: Highest precedence (first line) is 9, lowest precedence is 0. Operator listings aligned left, right, and center indicate left-, right-, and non-associativity.

Defining fixity:

infix  0-9 'op'    -- non associative
infixl 0-9 +-+     -- left associative
infixr 0-9 -!-     -- right associative
infixl 9           -- default (when none given)

Functions ≡ Infix operators

f a b     a 'f' b
a + b     (+) a b
(a +) b   ((+) a) b
(+ b) a   (\x -> x + b) a

Expressions / Clauses

If expression ≈ guarded equations

if boolExpr       foo ... | boolExpr = exprA
then exprA              | otherwise = exprB
else exprB

Nested if expression ≈ guarded equations

if boolExpr1      foo ... | boolExpr1 = exprA
then exprA              | boolExpr2 = exprB
else if boolExpr2       | otherwise = exprC
  then exprB
  else exprC

Case expression ≈ function pattern matching

case x of         foo pat1 = exA
  pat1 -> exA     foo pat2 = exB
  pat2 -> exB     foo _ = exC
  _ -> exC

2-variable case expression ≈ function pattern matching

case (x,y) of          foo pat1 patA = exprA
  (pat1,patA) -> exprA foo pat2 patB = exprB
  (pat2,patB) -> exprB foo _ _ = exprC
  _ -> exprC

Let expression ≈ where clause

let nameA = exprA foo ... = mainExpression
    nameB = exprB   where nameA = exprA
in mainExpression         nameB = exprB

Do notation ≈ desugarized do notation

do patA <- action1  action1 >>= \patA ->
   action2          action2 >>
   patB <- action3  action3 >>= \patB ->
   action4          action4

Pattern Matching (fn. declaration, lambda, case, let, where)

PatternDescriptionExample
fixednumber3
character'a'
ignore value_
empty string""
listempty[]
head x and tail xs(x:xs)
tail xs (ignore head)(_:xs)
list with 3 elements[a,b,c]
list where 2nd element is 3(x:3:xs)
tuplepair values a and b(a,b)
ignore second element(a,_)
triple values a, b and c(a,b,c)
mixedfirst tuple on list((a,b):xs)
maybejust constructorJust a
nothing constructorNothing
customuser-defined typeMyData a b c
ignore second fieldMyData a _ c
user-defined record typeMyR {f1=x, f2=y}
as-patterntuple s and its valuess@(a,b)
list a, its head and taila@(x:xs)

Prelude functions

Misc

id :: a -> a                      id x  x -- identity
const :: a -> b -> a              (const x) y  x
undefined :: a                    undefined  (lifts error)
error :: [Char] -> a              error cs  (lifts error cs)
not :: Bool -> Bool               not True False
flip :: (a -> b -> c) -> b -> a -> c
                                  flip f $ x y  f y x

Lists

null :: [a] -> Bool               null [] True -- ∅?
length :: [a] -> Int              length [x,y,z]  3
elem :: a -> [a] -> Bool          y 'elem' [x,y]  True -- ∈?
head :: [a] -> a                  head [x,y,z,w]  x
last :: [a] -> a                  last [x,y,z,w]  w
tail :: [a] -> [a]                tail [x,y,z,w]  [y,z,w]
init :: [a] -> [a]                init [x,y,z,w]  [x,y,z]
reverse :: [a] -> [a]             reverse [x,y,z]  [z,y,x]
take :: Int -> [a] -> [a]         take 2 [x,y,z]  [x,y]
drop :: Int -> [a] -> [a]         drop 2 [x,y,z]  [z]
takeWhile, dropWhile :: (a -> Bool) -> [a] -> [a]
                                  takeWhile (/= z) [x,y,z,w]  [x,y]
zip :: [a] -> [b] -> [(a, b)]
                                  zip [x,y,z] [a,b]  [(x,a),(y,b)]

Infinite Lists

repeat :: a -> [a]                repeat x  [x,x,x,x,x,x,...]
cycle :: [a] -> [a]               cycle xs  xs++xs++xs++...
                                  cycle [x,y]  [x,y,x,y,x,y,...]
iterate :: (a -> a) -> a -> [a]
                                  iterate f x  [x,f x,f (f x),...]

Higher-order / Functors

map :: (a->b) -> [a] -> [b]
                                  map f [x,y,z]  [f x, f y, f z]
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
                                  zipWith f [x,y,z] [a,b]  [f x a, f y b]
filter :: (a -> Bool) -> [a] -> [a]
                                  filter (/=y) [x,y,z]  [x,z]
foldr :: (a -> b -> b) -> b -> [a] -> b
                                  foldr f z [x,y]  x 'f' (y 'f' z)
foldl :: (a -> b -> a) -> a -> [b] -> a
                                  foldl f x [y,z]  (x 'f' y) 'f' z

Special folds

and :: [Bool] -> Bool             and [p,q,r]  p && q && r
or :: [Bool] -> Bool              or [p,q,r]  p || q || r
sum :: Num a => [a] -> a          sum [i,j,k]  i+j+k
product :: Num a => [a] -> a      product [i,j,k]  i*j*k
maximum :: Ord a => [a] -> a      maximum [9,0,5]  9
minimum :: Ord a => [a] -> a      minimum [9,0,5]  0
concat :: [[a]] ->[a]             concat [xs,ys,zs]  xs++ys++zs

Tuples

fst :: (a, b) -> a                fst (x,y)  x
snd :: (a, b) -> b                snd (x,y)  y
curry :: ((a, b) -> c) -> a -> b -> c
                                  curry (\(x,y) -> e)  \x y -> e
uncurry :: (a -> b -> c) -> (a, b) -> c
                                  uncurry (\x y -> e)  \(x,y) -> e

Numeric

abs :: Num a => a -> a            abs (-9)  9
even, odd :: Integral a => a -> Bool
                                  even 10 True
gcd, lcm :: Integral a => a -> a -> a
                                  gcd 6 8 2
recip :: Fractional a => a -> a   recip x  1/x
pi :: Floating a => a             pi  3.14...
sqrt, log :: Floating a => a -> a sqrt x  x**0.5
exp, sin, cos, tan, asin, acos :: Floating a => a -> a
truncate, round :: (RealFrac a, Integral b) => a -> b
ceiling, floor :: (RealFrac a, Integral b) => a -> b

Strings

lines :: String -> [String]
                                  lines "ab\ncd\ne" ["ab","cd","e"]
unlines :: [String] -> String
                                  unlines ["ab","cd","e"]  "ab\ncd\ne\n"
words :: String -> [String]
                                  words "ab cd e" ["ab","cd","e"]
unwords :: [String] -> String
                                  unwords ["ab","cd","ef"]  "ab cd ef"

Read and Show classes

show :: Show a => a -> String     show 137 "137"
read :: Show a => String -> a     read "2" 2

Ord Class

min :: Ord a => a -> a -> a       min 'a' 'b'  'a'
max :: Ord a => a -> a -> a       max "b" "ab" "b"
compare :: Ord a => a->a->Ordering
                                  compare 1 2 LT

IO – Must be “inside” the IO Monad

putChar c       -- Write char c to stdout
putStr cs       -- Write string cs to stdout
putStrLn cs     -- Write string cs to stdout w/ a newline
print x         -- Print x, a show instance, to stdout
getChar         -- Read char from stdin
getLine         -- Read line from stdin as a string
getContents     -- Read all input from stdin as a string
interact foo    -- Bind stdin/out to foo (:: String -> String)
writeFile fn cs -- Write string cs to a file named fn
appendFile fn cs -- Append string cs to a file named fn
readFile fn     -- Read contents from a file named fn

List Comprehensions

Take pat from list. If boolPredicate, add element expr to list:

[expr | pat <- list, boolPredicate, ...]
 
[x | x <- xs]                  xs
[f x | x <- xs, p x]           map f $ filter p xs
[x | x <- xs, p x, q x]        filter q $ filter p xs
[x+y | x <- [a,b], y <- [i,j]]  [a+i, a+j, b+i, b+j]
[x | boolE]                    if boolE then [x] else []

Libraries / Modules

-- importing
import Some.Module
import qualified Some.Module as SM
import Some.Module (foo,goo)
import Some.Module hiding (foo,goo)
import Some.Module ()
 
-- declaring
module Module.Name
  ( foo, goo )
where
  ...
 
-- File path
./File/On/Disk.hs  import File.On.Disk

Tracing and monitoring (unsafe) Debug.Trace

trace string $ expr    -- Print string, return expr
traceShow expr $ expr  -- Call show before printing
traceShow (x,y) False  -- Trace function f x y values

GHC - Glasgow Haskell Compiler (and Cabal)

$ ghc program.hs             -- compiling program.hs
$ ./program                  -- running
$ run_haskell program.hs     -- running directly
$ ghci                       -- interactive mode (GHCi)
> :l program.hs              -- GHCi load
> :r                         -- GHCi reload
> :set +s                    -- GHCi activate stats
> :?                         -- GHCi help
> :t expr                    -- Type of an expression
> :i thing                   -- Info (oper./func./class)
$ ghc-pkg list [pkg_name]    -- Installed GHC packages
{-# LANGUAGE Pragma #-}      -- Activating some pragma
$ ghc -XSomePragma ...       -- Same, via GHC call
$ cabal install pkg          -- install package pkg
$ cabal update               -- update package list
$ cabal list pat             -- list packages matching pat
$ cabal info pkg             -- information about package
$ cabal help [command]       -- help on commands
$ cabal run/test/bench [name] -- run executable/test/bench
$ cabal sandbox init         -- initialize sandbox
$ cabal sandbox add-source dir -- add custom sandbox source

Copyright 2014-2021, Rudy Matela – Compiled on November 8, 2021
Upstream: https://github.com/rudymatela/concise-cheat-sheets Basic Haskell Cheat Sheet v1.2
This text is available under the Creative Commons Attribution-ShareAlike 3.0 Licence,
or (at your option), the GNU Free Documentation License version 1.3 or Later.