Haskell Intro Examples
Basics
Math
3+4
5*6
2^10
2^100
3/4
9 `mod` 5
Lists and Ranges
[]
[2]
[2,3,5]
[2,3,5] ++ [6,7]
'a'
['a']
['a','b']
"hello" ++ "world"
[1..20]
Functions
sqrt 5
even 5
even 6
head [1,2,3,4]
head "hello"
take 0 [1,2,3,4]
take 1 [1,2,3,4]
take 2 [1,2,3,4]
take 2 "hello"
Types
:t True
:t 'a'
:t "abc"
:t 42
:t [2,3,4]
:t 3.14
:t sqrt
:t even
:t head
:t take
First-Order Functions
Currying
take2 = take 2
:t take2
take2 [1,2,3,4]
:t (^)
:t (2^)
:t (^2)
(^2) 3
(2^) 3
square = (^2)
pow2 = (2^)
Filter
:t filter
filter odd [0..10]
filter even [0..10]
evens = filter even
evens [0.10]
Map
:t map
map even [0..10]
map square [0..10]
map square (filter odd [0..10])
map square $ filter odd [0..10]
Recursive Definitions
Lists w/ Cons
2:[]
2:3:5:[]
4:[2,3,5]
List Functions
head [1,2,3,4]
tail [1,2,3,4]
length [1,2,3,4]
reverse [1,2,3,4]
List Patterns
In ghci
, use :{
and :}
to wrap multiline definitions.
len [] = 0
len (x:xs) = 1 + (len xs)
rev [] = []
rev (x:xs) = (rev xs)++[x]
Miscellaneous Haskell Novelties
Conditional Expressions
if (even 6) then "even" else "odd"
if (even 7) then "even" else "odd"
Let Clauses
nextOdd x = if odd (x+1) then x+1 else x+2
nextOdd x = let y=x+1 in if odd y then y else y+1
oddsGreaterThan x = let y = nextOdd x in y:(oddsGreaterThan y)
oddsGreaterThan 9
Lazy Evaluation
take 5 (oddsGreaterThan 9)
take 5 $ oddsGreaterThan 9
Quicksort
With filter
:
qsort [] = []
qsort (x:xs) = (qsort $ filter (<=x) xs)
++ [x] ++
(qsort $ filter (>x) xs)
With list comprehensions:
qsort [] = []
qsort (x:xs) = qsort [y | y <- xs, y <= x]
++ [x] ++
qsort [y | y <- xs, y > x]