Here I’ll post the code for my solutions to the 1st chapter of the book.
1.1
|
|
1.2
|
|
1.3
The function expression for g
is of type int -> int
and the function expression for h
is (float * float) -> float
1.4
The recusion formula for the following problem is:
|
|
The code for the assignment:
|
|
The evaluation for f 3 is as follows:
|
|
1.5
The naive implementation of the solution to the problem would look like the code below.
This solutions is however problematic because the recursion tree would expand exponentially.
This due to the fact you call fib (n -1) + fib (n -2)
and thus you do two recursive calls for each level
(if you imangine it as a tree) of your fibonacci sequence.
|
|
A better approach would be to utilize the concept of tail-recusion when solving the task, but this is unlikely the reader knows that at this point in the book. This would convert the recursive call into simple goto statements and thus avoid the exponetial stack growth as the previous solution. The new solution would the look something like this:
|
|
The evaluation for fib 4 is as follows for the naive solution:
|
|
1.6
The recursion formula for the following problem is:
|
|
The code for the solution:
|
|
1.7
The type for the expressions is: (System.Math.PI, fact -1) = (float * int) fact(fact 4) = int power(System.Math.PI, fact 2) = float (power, fact) = (float -> int -> float) * (int -> int))
Photo by Ilija Boshkov on Unsplash