You are on page 1of 4

BBM 301 - Programming Languages - Fall 2020

Assignment 2

Due Date: 10 January 2021, 23:59

Name: Ömer Salih Pakdil

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)

The function sum-of-squares computes the sum of the first x squares:

let rec sum-of-squares n =


if n=0 then 0
else n*n + sum-of-squares(n-1);; Not tail recursion
val sum-of-squares : int -> int = <fun>
We can accumulator technique to make sum-of-squares tail-recursive.

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))))))

b) Tail Recursive Func:

(define (factorial n)
(acc-factorial n 1))0

(define (acc-factorial n sofar)


(if (zero? n)
sofar
(acc-factorial (- n 1) (* sofar n))))

c) Step through the evaluation:

(+ (factorial 3) (factorial 2) (factorial 5) (factorial 1) (factorial 4) => 153

Task4: Iterative func sum-of-squares:

(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))))

(define (sum-of-factorials-of-elements lst)


(do ((i (length lst) (- i 1))

Task6: Compare:
Time complexity Space Complexity
sum-of-squares:

iterative-> O(n) O(1)


recursive-> O(1) O(n)
tail recursive -> O(n) O(n)

You might also like