Solutions to Haskell from First Principles
This is just one of many textbooks I'm working through on my quest to learn Haskell.
Chapter 1. Anything from Almost Nothing
1. $${(\lambda a b c . c b a)zz(\lambda w v.w)}$$ (Currying for clarity) $${(\lambda a . \lambda b . \lambda c . cba)(z)z(\lambda w . \lambda v.w)}$$ (Eliminate the head and apply the variiable) $${(\lambda b. \lambda c. cbz)(z)(\lambda w. \lambda v.w)}$$ (Eliminate from left to right, etc) $${(\lambda c. czz)(\lambda w. \lambda v.w)}$$ $${(\lambda w. \lambda v.w)(z)z}$$ $${(\lambda v . z)(z)}$$ (Becoming the singular:) $${z}$$ 2. $${(\lambda x. \lambda y.xyy)(\lambda a.a)b}$$ $${\lambda y.(\lambda a.a)yy)b}$$ $${\lambda a.a)(b)b}$$ $${b.b}$$Chapter 2. Basic expressions and functions
Most arithmetic functions in Haskell (and math) are left-associative. So 2*3*4 is evaluated as (2*3)*4. Exponentiation is right-associative, so 2 ^ 3 ^ 4 is evaluated as 2 ^ ( 3 ^ 4). Unlike multiplication, which is commutative and not affected by order of operations, which expression we evaluate with exponentiation is more important. i.e.:
2 ^ 3 ^ 4
2417851639229258349412352
Whereas
(2 ^ 3) ^ 4
4096
Exercises: Parentheses and Association:
Here's some revision testing our intuitions around order-of-operations. In Haskell, we can get a numerical representation of the priority of an infix operator by running :info
. i.e. :info (*)
7 *
1.
a) 8+7 *9
b) (8+7)* 9
Yes, parentheses change the evaluation of this equation.
2.
a) perimeter x y = (x *2) + (y+2)
b) perimeter x y = x * 2 + y * 2
No, as multiplication is already prioritised over addition, the evaluation result should be the same.
3.
a) f x = x / 2 + 9
b) f x = x / (2 + 9)
Yes, a
will evaluate x / 2
first, while b will evaluate (2 + 9)
first.