● New variables with "let" declaration, lifetime inside the declaration Variables in ● Variables are always initialized Haskell test n = let k = fact n in [1..k] ● Other ways exist, for example "inverted" where declaration: test n = [1..k] where k = fact n 52
● No reference parameters, all results in the return value Haskell ● Multiple return values using tuples , which tuples contain an arbitrary number of values (of different types) division x y = ( x div y, x mod y ) ● A tuples allows initialization of multiple variables let (result, remainder) = division 10 4 in ... ● Tuples also in many other languages (C+ +11, Python...) 53
● Only possible, because data is guaranteed not to change Sharing data ● Example: a list: orig = [A, B, C, D] orig A B C D 54
● A new item is "added" to beginning: a new list is returned Sharing data ● newlist = (X : orig) ([X, A, B, C, D]) orig A B C D newlist X 55
● A new item is "added" in the middle: ● newlist2 = (take 2 orig) ++ [Y] ++ Sharing data (drop 2 orig) ([ A, B, Y, C, D]) orig A B C D newlist2 Y 56
● Infinite computation possible (prevents concurrent evaluation) Effects of noreturn x = maximum [x..] laziness choose T rue x y = x choose False x y = y choose (1<3) 3 (noreturn 5) ➜ 4 3 choose (4<3) 3 (noreturn 5) ➜ 4 ... ● Recursive variable definitions ones = 1:ones nums = 0:[a+1 | a <- nums] fibo = 1:1:[a+b | (a,b) <- zip fibo (tail fibo)] 57
● value of each expression is a "thunk" describing the function & parameters: Implementing x = 3; a = [f(x), g(x)] ; b = head lazy a evaluation b a variable value thunk head: take 1st function f(x) = 2*x x 3 g(x) = x+3 58
● "execution" of functions only happen when the value of its return value is Implementing required: lazy print b; evaluation b a head: take 1st f(x) = 2*x x 3 g(x) = x+3 59
● Note! We didn't calculate the whole a to get the result!: Implementing print b; lazy evaluation b a head: take 1st 6 f(x) = 2*x x 3 g(x) = x+3 60
Recommend
More recommend