Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion Scheme

I have a formula, (2^n)-1, and I need to convert it to a recursion function, I tried several times to rewrite it, but I'm still struggling. What is wrong with my code?

(define fnum(n)
    (if (= n 0) 0
        (- ( * 2 (fnum (- n 1)) 1)))

(fnum (- n 1)))
like image 977
Anastasia Cmp Avatar asked Dec 07 '25 18:12

Anastasia Cmp


2 Answers

You can do it like this (working example):

(define pow
  (lambda (n)
    (if (= n 0)
      1
      (* 2 (pow (- n 1))))))

(display (- (pow 5) 1)) 

It is clear that you should split the powering part with the minus 1 step which is going to be performed afterwards.

like image 75
NiVeR Avatar answered Dec 09 '25 20:12

NiVeR


You need to split the recursion from the substraction:

(define (parent-nodes-helper n)
  (if (= n 0) 
      0
      (* 2 (parent-nodes-helper (- n 1)))))

;;; Number of parent nodes in a perfect balanced binary tree
(define (parent-nodes depth)
  (- (parent-nodes-helper depth) 1))

Now. The helper can be made local to fnum and even be implemented as named let and then you can add acc parameter to hold the result so that the multiplication doesn't need to be done after each recusion ends. Here is a how I would do it:

;;; Number of parent nodes in a perfect balanced binary tree
(define (parent-nodes depth)
  (let loop ((n depth) (acc 1))
    (if (zero? n) 
        (- acc 1)
        (loop (- n 1) (* acc 2)))))

It's common to call an iterative tail recursion in named let loop, but I could have kept the name parent-nodes-helper or whatever I found fitting. It's just a name.

like image 29
Sylwester Avatar answered Dec 09 '25 22:12

Sylwester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!