Side effects
def fib(n):
x1 = 0
x2 = 1
for i in range(n):
tmp = x2
x2 = x1 + x2
x1 = tmp
return x1
No side effects
(define (fib n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2)))))
Int, Integer, Rational, Float, etc
ghci> (50 * 100) - 4999
1
ghci> 50 * 100 - 4999
1
ghci> 50 * (100 - 4999)
-244950
Denoted with singe quotes
True
or
False
ghci> min 5 6 + max 10 20
25
ghci> min 5 max 3 4
-- Crash!
ghci> min 6 (max 3 4)
4
let
in GHCi
ghci> let pi = 3.14
ghci> let area r = pi * r ^ 2
ghci> area 5
78.5
ghci> let hypot x y = sqrt (x ^ 2 + y ^ 2)
ghci> hypot 3 4
5.0
area r =
let pi = 3.14
in pi * r ^ 2
area r = pi * r ^ 2
where pi = 3.14
ghci> head [1, 2, 3, 4]
1
ghci> tail [1, 2, 3, 4]
[2, 3, 4]
head
is like
car
tail
is like
cdr
:
is like
cons
ghci> 1:[2, 3, 4]
[1, 2, 3, 4]
ghci> [1, 2] ++ [3, 4]
[1, 2, 3, 4]
ghci> [1, 2] ++ [3, 4]
[1, 2, 3, 4]
ghci> [1, 2, 3, 4] !! 1
2
ghci> ['h', 'e', 'l', 'l', 'o'] ++ " world"
"hello world"
ghci> [1..9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
ghci> [1, 3..9]
[1, 3, 5, 7, 9]
ghci> ['a'..'e']
"abcde"
ghci> let evens = [0, 2..]
ghci> evens !! 10
20
ghci> (1, 'a', [3.0])
(1, 'a', [3.0])
ghci> zip [1, 2, 3] "abc"
[(1, 'a'), (2, 'b'), (3, 'c')]
Let’s define !! recursively
nth lst n =
if n == 0
then head lst
else nth (tail lst) (n - 1)
Woohoo, it looks like Lisp
But we can do better…
nth lst 0 = head lst
nth lst n = nth (tail lst) (n - 1)
Ooh, that’s pretty
But we can do better…
Note: _ typically means ignored variable
nth (h:_) 0 = h
nth (_:t) n = nth t (n - 1)
We can even pattern match tuples
flipTuple (x, y) = (y, x)
Backticks allow infix notation
ghci> nth [1, 2, 3] 1
ghci> [1, 2, 3] `nth` 1
(define (collatz-next n)
(if (even? n)
(/ n 2)
(+ 1 (* 3 n))))
No, but we can use guards
collatzNext n =
| even n = n / 2
| otherwise = 3 * n + 1
Let’s double all elements in a range
Lisp
(map (lambda (x) (* x 2)) (range 1 11))
Haskell
[x * 2 | x <- [1..10]]
Let’s double all multiples of 7 less than 100
Lisp
(map (lambda (x) (* x 2))
(filter (lambda (x) (zero? (mod x 7)))
(range 1 11)))
[x * 2 | x <- [1..10], x `mod` 7 == 0]
map, filter, and foldl still exist of course