Professional Documents
Culture Documents
Assignment 2
ID: 21727647
Task1:
Steps:
1) First we need to convert the original function to a local helper function.
2) We also need to add an accumulator argument to the helper function.
3) Then we have to change the recursive call of the helper function to the tail
recursive call and make sure you update the accumulator accordingly.
4) Finally we just need to make one call to the helper with the proper initial
values for the main function body.
Few out of every odd recursive function can be transformed into a tail-recursive
function. In particular,if a function settles on a recursive call, however then inspects
the outcome and does various things relying upon its worth, at that point it may not be
conceivable to make the function tail-recursive.
Task2:
a)
let sum-of-tail n =
let rec sum-of-squares-2 n acc =
if n=0 then acc
else sum-of-squares-2 (n-1)(acc+n*n)
in sum-of-squares-2 (n) 0;
val sum-of-tail : int -> int = <fun>
b)
on (list 1 2 3 4 5)
- (sum-of-squares 5)
original version :
(+ 1 (+ 4 (+ 9 (+ 16 (+ 25 0))))) => 55
accumulator-style version:
(+ 1 0) => 1
(+ 4 1) => 5
(+ 9 5) => 14
(+ 16 14) => 30
(+ 25 30) => 55
Task3:
a) Recursive func:
(define sum_of_factorials_of_elements
(lambda (lst)
(if (null? lst)
0
(+ (factorial (car lst))
(sum_of_factorials_of_elements (cdr lst))))))
(define (factorial n)
(acc-factorial n 1))0
(define (squareOfSums n)
(sqr (/ (* n (+ n 1)) 2)))
Task5: Iterative func sum-of-factorial-of-elements:
(define (factorial n)
(do ((i 1 (+ i 1))
(fact 1)) ((> i n ) fact)
(set! fact(* fact i))))
Task6: Compare:
Time complexity Space Complexity
sum-of-squares: