Question

Is the following function tail-recursive? If not, what might I do to modify it?

(define (euclids-alg n1 n2)
 (cond((= n1 0) n2)
      ((= n2 0) n1)
      ((= n1 n2) n1)
      ((> n1 n2) (euclids-alg (- n1 n2) n2))
      ((< n1 n2) (euclids-alg n1 (- n2 n1))))) 
Was it helpful?

Solution

Yes, your function is tail recursive, because the recursive call is in tail position - meaning, it's the last thing it's done after the recursion returns. Take a look at the specification to better understand when we have a valid tail call and when we don't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top