Sie sind auf Seite 1von 2

Basic Haskell Cheat Sheet

Declaring Types and Classes


type synonym

Structure
func :: type -> type
func x = expr

data (single constructor)

fung :: type -> [type] -> type


fung x xs = expr

data (multi constructor)

main = do code
code
...

typeclass

Function Application
f
f
f
f
f
f

x
x
$
$
$
g

y
y
g
g
g
$

$ h x
x y

h x

typeclass instance

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

((f) (x)) (y)


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

Values and Types


has type
boolean
character
fixed-precision integer
integer (arbitrary sz.)
single precision float
double precision float
list

string
tuple
ordering relation
function ()

expr
True || False
a
1
31337
31337^10
1.2
1.2
[]
[1,2,3]
[a,b,c]
"abc"
[[1,2],[3,4]]
"asdf"
(1,2)
([1,2],a)
LT, EQ, GT
\x -> e

::
::
::
::
::
::
::
::
::
::
::
::
::
::
::
::
::
::

type
Bool
Char
Int
Integer
Integer
Float
Double
[a]
[Integer]
[Char]
[Char]
[[Integer]]
String
(Int,Int)
([Int],Char)
Ordering
a -> a

Values and Typeclasses


given context, has type
Numeric (+,-,*)
Fractional (/)
Floating
Equatable (==)
Ordered (<=, >=, >, <)

expr
137
1.2
1.2
a
731

::
::
::
::
::
::

context => type


Num a => a
Fractional a => a
Floating a => a
Eq a => a
Ord a => a

Common functions

type
type
type
type
type
data

MyType = Type
UserId = Integer
UserName = String
User = (UserId,UserName)
UserList = [User]
MyData = MyData Type Type Type
deriving (Class,Class )
data MyData = Simple Type |
Duple Type Type |
Nople
class MyClass a where
foo :: a -> a -> b
goo :: a -> a
...
instance MyClass MyType where
foo x y = ...
goo x = ...
...

Operators (grouped by precedence)


List index, function composition
!!,
.
raise to: Non-neg. Int, Int, Float
^, ^^, **
multiplication, fractional division
*, /
integral division ( ), modulus div, mod
integral quotient ( 0), remainder
quot, rem
addition, subtraction
+, list construction, append lists
:, ++
list difference
\\
comparisons:
>, >=, <, <=, ==, /=
list membership
elem, notElem
boolean and
&&
boolean or
||
sequencing: bind and then
>>=, >>
application, strict apl., sequencing
$, $!, seq
NOTE: Highest precedence (first line) is 9, lowest precedence is 0. Those
aligned to the right are right associative, all others left associative: except comparisons, list membership and list difference which are nonassociative. Default is infixl 9.

Misc
id
const
undefined
error
not
flip

::
::
::
::
::
::

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

Tuples
fst
snd
curry

:: (a, b) -> a
fst (x,y ) x
:: (a, b) -> b
snd (x,y ) y
:: ((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

Lists
null
head
tail
init
reverse
take
drop
length
elem
repeat
cycle

::
::
::
::
::
::
::
::
::
::
::

[a] -> Bool


null [] True -- empty?
[a] -> a
head [x,y,z,w ] x
[a] -> [a]
tail [x,y,z,w ] [y,z,w ]
[a] -> [a]
init [x,y,z,w ] [x,y,z ]
[a] -> [a]
reverse [x,y,z ] [z,y,x ]
Int -> [a] -> [a] take 2 [x,y,z ] [x,y ]
Int -> [a] -> [a] drop 2 [x,y,z ] [z ]
[a] -> Int
length [x,y,z ] 3
a -> [a] -> Bool
y elem [x,y ] True -- ?
a -> [a]
repeat x [x,x,x,...]
[a] -> [a]
cycle xs xs ++xs ++...

Special folds
and
or
sum
product
concat
maximum
minimum

::
::
::
::
::
::
::

[Bool] -> Bool


[Bool] -> Bool
Num a => [a] ->
Num a => [a] ->
[[a]] ->[a]
Ord a => [a] ->
Ord a => [a] ->

a
a
a
a

and [p,q,r ]
or [p,q,r ]
sum [i,j,k ]
product [i,j,k ]
concat [xs,ys,zs ]
maximum [10,0,5]
minimum [10,0,5]

p && q &&r
p || q ||r
i + j + k
i * j * k
xs ++ys ++zs
10
0

Defining fixity
non associative fixity
left associative fixity
right associative fixity
default, implied when no fixity given

Functions Infix operators


f a b

a + b

(a +) b
(+ b) a

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

Copyright 2014, Rudy Matela Compiled on October 26, 2014 Upstream: https://github.com/rudymatela/ultimate-cheat-sheets

infix 0-9 op
infixl 0-9 +--+
infixr 0-9 -!infixl 9

Higher-order / Functors
map

:: (a->b) -> [a] -> [b]


map f [x,y,z ] [f x, f y, f z ]

filter :: (a -> Bool) -> [a] -> [a]


filter (/=y) [x,y,z ] [x,z ]
foldl

:: (a -> b -> a) -> a -> [b] -> a


foldl f x [y,z ] (x f y ) f z

foldr

:: (a -> b -> b) -> b -> [a] -> b


foldr f z [x,y ] x f (y f z )

This text is avaliable under the Creative Commons Attribution-ShareAlike 3.0 Licence, or, the GNU Free Documentation License version 1.3 or Later.

Numeric

Expressions / Clauses

IO Must be inside the IO Monad

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

Write char c to stdout


Write string cs to stdout
Write string cs to stdout w/ a newline
Print x, a show instance, to stdout
Read char from stdin
Read line from stdin as a string
Read all input from stdin as a string
Bind stdin/stdout to foo (:: String -> String)
Write string cs to a file named fn
Append string cs to a file named fn
Read contents from a file named fn

putChar c
putStr cs
putStrLn cs
print x
getChar
getLine
getContents
interact foo
writeFile fn cs
appendFile fn cs
readFile fn

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
read :: Show a => String -> a

show 137 "137"


read "2" 2

Pattern Matching
Simple Pattern Matching
Number 3
Empty string

3
""

Character a
Ignore value

List Pattern Matching


empty list
head x and tail xs
tail xs (ignore head)
list with 3 elements a, b and c
list where 2nd element is 3

[]
(x:xs)
( :xs)
[a,b,c]
(x:3:xs)

Patterns for Tuples and Other Types


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

Libraries / Modules
importing
importing (qualified)
importing (subset)
declaring

./File/On/Disk.hs

import PathTo.Lib
import PathTo.Lib as PL
import PathTo.Lib (foo,goo )
module Module.Name
( foo
, goo
)
where
...
import File.On.Disk

Tracing and monitoring (unsafe)


Print string, return expr
Call show before printing
Trace function fun x y
call values
fun x y

pair values a and b


ignore second element of tuple
triple values a, b and c
just constructor
nothing constructor
user-defined type
ignore one of the components
match first tuple on list

(a,b)
(a,_)
(a,b,c)
Just a
Nothing
MyData a b c
MyData a _ c
((a,b):xs)

match entire tuple s its values a,b


match entire list a its head x and tail xs
entire data p and components

s@(a,b)
a@(x:xs)
p@(MyData a b c)

List Comprehensions

trace string $ expr


traceShow expr $ expr
| traceShow (x,y) False = undefined
= ...

[x |
[f x
[x |
[f x
[x+y

x
|
x
y
|

<- xs]
x <- xs, p x]
<- xs, p x, q x]
| x <- xs, y <- ys]
x <- [a,b], y <- [i,j]]

Copyright 2014, Rudy Matela Compiled on October 26, 2014 Upstream: https://github.com/rudymatela/ultimate-cheat-sheets

guarded equations
foo ... | boolExpr = exprA
| otherwise = exprB

nested if expression
if boolExpr1
then exprA
else if boolExpr2
then exprB
else exprC

guarded equations
foo ... | boolExpr1 = exprA
| boolExpr2 = exprB
| otherwise = exprC

case expression
case x of
pat1 -> exprA
pat2 -> exprB
-> exprC

function pattern matching


foo pat1 = exprA
foo pat2 = exprB
foo
= exprC

2-variable case expression


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

function pattern matching


foo pat1 patA = exprA
foo pat2 patB = exprB
= exprC
foo

let expression
let nameA =exprA
nameB =exprB
...
in mainExpression

where clause
foo ... = mainExpression
where nameA =exprA
nameB =exprB
...

do notation
do statement
pat <- exp
statement
pat <- exp
...

desugarized do notation
statement >>
exp >>= \pat ->
statement >>
exp >>= \pat ->
...

statement separator
statement grouping

;
{ }

-- or line break
-- or layout/indentation

GHC - Glasgow Haskell Compiler (and Cabal)

As-pattern

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


[expr | pat <- list, boolPredicate, ...]

Debug.Trace

if expression
if boolExpr
then exprA
else exprB

xs
map f $ filter p xs
filter q $ filter p xs
zipWith f xs ys
[a+i, a+j, b+i, b+j]

compiling program.hs
running
running directly
interactive mode (GHCi)
GHCi load
GHCi reload
GHCi activate stats
GHCi help
Type of an expression
Info (oper./func./class)
install package pkg
update package list
list/search for packages matching pat
information about package pkg

$
$
$
$
>
>
>
>
>
>
$
$
$
$

ghc program.hs
./program
run haskell program.hs
ghci
:l program.hs
:r
:set +s
:?
:t expr
:i thing
cabal install pkg
cabal update
cabal list pat
cabal info pkg

This text is avaliable under the Creative Commons Attribution-ShareAlike 3.0 Licence, or, the GNU Free Documentation License version 1.3 or Later.