You are on page 1of 2

Ultimate Haskell Cheat Sheet Declaring Types and Classes Common functions

type synonym type MyType = Type Lists (and Strings (which are lists...))
Structure type UserId = Integer
type UserName = String head / first element of xs head xs
func :: type -> type type User = (UserId,UserName) tail (rest) of xs tail xs
func x = expr type UserList = [User] elements of xs except last init xs
data (single constructor) data MyData = MyData Type Type Type first n elements of xs take n xs
fung :: type -> [type] -> type deriving (Class,Class ) excludes first n elements of xs drop n xs
fung x xs = expr data (multi constructor) data MyData = Simple Type | checks for x in xs x ‘elem‘ xs
Duple Type Type | is xs null/empty? null xs
main = do code Nople size / length of xs length xs
code typeclass class MyClass a where invert / reverse of xs reverse xs
... foo :: a -> a -> b sorts xs sort xs
goo :: a -> a pairs (x,y) from xs and ys zip xs ys
... infinite repetition of xs cycle xs
Function Application and of booleans in xs and xs
or of booleans in xs or xs
f x y (f x) y sum of numbers in xs sum xs
f x y z ((f x) y) z Operators (grouped by precedence) product of numbers in xs product xs
f g $ h x f g (h x) concatenates list of lists xs concat xs
f $ g x y f (g x y) List index, function composition !!, . largest element in xs maximum xs
f $ g $ h x f (g (h x)) raise to: Non-neg. Int, Int, Float ^, ^^, ** smallest element in xs minimum xs
(f . g . h) x f (g (h x)) multiplication, fractional division *, /
integral division (⇒ −∞), modulus ‘div‘, ‘mod‘
integral quotient (⇒ 0), remainder ‘quot‘, ‘rem‘ Tuples
Binding Types addition, subtraction +, - first of pair p fst p
list construction, append lists :, ++ second of pair p snd p
has type expr :: type
list difference \\ swap pair p swap p
boolean True || False :: Bool
comparisons: >, >=, <, <=, ==, /=
character ’a’ :: Char
list membership ‘elem‘, ‘notElem‘
fixed-precision integer 1 :: Int
integer (arbitrary sz.) 31337 :: Integer
boolean and && Higher-order / Functors
31337^10 :: Integer boolean or ||
sequencing: bind and then >>=, >> apply f to each x in xs map f xs
single precision float 1.2 :: Float fold - (z ‘f‘ left) ‘to‘ right foldl f z xs
double precision float 1.2 :: Double application, strict apl., sequencing $, $!, seq
:: (a -> b -> a) -> a -> [b] -> a
list [] :: [a] NOTE: Highest precedence (first line) is 9, lowest precedence is 0. fold - right ‘to‘ (left ‘f‘ z) foldr f z xs
[’a’,’b’,’c’] :: [Char] Those aligned to the right are right associative, all others left associa- :: (a -> b -> b) -> b -> [a] -> b
"abc" :: [Char] tive: except comparisons, list membership and list difference which are filter all xs satisfying p xs filter p xs
[[1,2],[3,4]] :: [[Integer]] non-associative. Default is infixl 9.
tuple (1,2) :: (Int,Int)
([1,2],’a’) :: ([Int],Char)
string "asdf" :: String Defining fixity IO – Must be “inside” the IO Monad
functions foo :: a -> a
double :: Int -> Int non associative fixity infix 0-9 ‘op‘ Write char c to stdout putChar c
left associative fixity infixl 0-9 +--+ Write string cs to stdout putStr cs
right associative fixity infixr 0-9 -!- ... cs ... with a newline putStrLn cs
Binding Classes (Typeclasses) default, implied when no fixity given infixl 9 Print x, a show instance2 , to stdout print x
Read char from stdin getChar
Numeric (+,-,*,/) 137 :: Num a => a Read line from stdin as a string getLine
Floating 1.2 :: Floating a => a Functions ≡ Infix operators Read all input from stdin as a string getContents
Fractional 1.2 :: Fractional a => a Make foo process the input interact foo
Equatable (==) ’a’ :: Eq a => a :: (String -> String) -> IO ()
Ordered (<=, >=, >, <) 731 :: Ord a => a f a b a ‘f‘ b Write char c to channel/file h hPutChar h c
sort :: Ord a => [a] -> [a] a + b (+) a b Write string cs to channel/file h hPutStr h cs
Bounded (minBound,maxBound) minBound :: Int (a +) b ((+) a) b ... cs ... with a newline ... to h hPutStrLn h cs
(+ b) a (\x -> ((+) x b)) a

Copyright 2014, Rudy Matela – Compiled on March 19, 2014 – Upstream: https://github.com/rudymatela/ultimate-cheat-sheets This text is avaliable under the Creative Commons Attribution-ShareAlike 3.0 Licence, or, the GNU Free Documentation License version 1.3 or Later.
Pattern Matching Expressions (Eval. control) QuickCheck Test.Quickcheck
declaring property prop something :: a -> Bool
Simple Pattern Matching statement separator ; -- or line break
prop something :: a -> Property
statement grouping { } -- or layout/indentation
Number 3 3 verifying property quickCheck prop something
Character ’a’ ’a’ if expression if expr :: Bool
Empty string "" then expr :: a SmallCheck Test.SmallCheck
else expr :: a verifying property smallCheck depth prop something
List Pattern Matching
case expression case expr of
head x and tail xs (x:xs) pat -> expr HUnit Test.HUnit
empty list [] pat -> expr equality assertion expected ~=? actual
list with 3 elements a, b and c [a,b,c] ... testlist mytestlist =
list with 3 elements a, b and c (a:b:c:[]) -> expr TestList [ expec ~=? actual
list where 2nd element is 3 (x:3:xs) , expec ~=? actual
let expression let name =expr ...
Other Types Pattern Matching name =expr , expec ~=? actual ]
... running tests runTestTT mytestlist
pair values a and b (a,b) in expr
triple values a, b and c (a,b,c)
just constructor Just a where notation expr Language Pragmas
nothing constructor Nothing where name =expr
user-defined type MyData a b c Activating some pragma {-# LANGUAGE SomePragma #-}
name =expr
Same, via GHC call ghc -XSomePragma ...
...
No monomorphism restriction NoMonomorphismRestriction
Wildcard Pattern “Matching” Scoped type variables ScopedTypeVariables
do notation do statement
Template Haskell TemplateHaskell
ignore value _ pat <- exp
ignore first elements of list (_:xs) statement
ignore second element of tuple (a,_) pat <- exp GHC - Glasgow Haskell Compiler
ignore one of the “componenet” MyData a _ c ...
compiling program.hs $ ghc program.hs
pattern matching f :: a -> b -> c running $ ./program
Nested Pattern running directly $ run haskell program.hs
(case sugar) f pat pat = expr
match first tuple on list ((a,b):xs) f _ pat = expr interactive mode (GHCi) $ ghci
match list inside tuple (xs,y:ys,zs) f pat _ = expr GHCi load > :l program.hs
f _ _ = expr GHCi reload > :r program.hs
GHCi activate stats > :set +s
As-pattern
guarded equations name GHCi turn off stats > :unset +s
match entire tuple s its values a,b s@(a,b) | boolexpr = expr GHCi help > :?
match entire list a its head x and tail xs a@(x:xs) | boolexpr = expr Type of an expression > :t expr
entire data p and “components” p@(MyData a b c) | boolexpr = expr Info (oper./func./class) > :i thing

List Comprehensions Libraries / Modules Cabal package and build system


pairs where sum=4 [(x,y) | install package pkg $ cabal install pkg
importing import PathTo.Lib update package list $ cabal update
x <- [0..4],
importing (qualified) import PathTo.Lib as PL list/search for packages matching pat $ cabal list pat
y <- [0..4],
importing (subset) import PathTo.Lib (foo,goo ) information about package pkg $ cabal info pkg
x + y == 4]
declaring module Module.Name help on commands $ cabal help [command]
== [(0,4),(1,3),(2,2),...]
( foo
, goo
)
where
...

./File/On/Disk.hs import File.On.Disk

Copyright 2014, Rudy Matela – Compiled on March 19, 2014 – Upstream: https://github.com/rudymatela/ultimate-cheat-sheets This text is avaliable under the Creative Commons Attribution-ShareAlike 3.0 Licence, or, the GNU Free Documentation License version 1.3 or Later.

You might also like