Recursing in a lambda function

后端 未结 3 1343
不知归路
不知归路 2021-02-07 09:06

I have the following 2 functions that I wish to combine into one:

(defun fib (n)
  (if (= n 0) 0 (fib-r n 0 1)))

(defun fib-r (n a b)
  (if (= n 1) b (fib-r (-          


        
3条回答
  •  余生分开走
    2021-02-07 09:50

    You can try something like this as well

    (defun fib-r (n &optional (a 0) (b 1) )
      (cond
        ((= n 0) 0)
        ((= n 1) b)
        (T (fib-r (- n 1) b (+ a b)))))
    

    Pros: You don't have to build a wrapper function. Cond constructt takes care of if-then-elseif scenarios. You call this on REPL as (fib-r 10) => 55

    Cons: If user supplies values to a and b, and if these values are not 0 and 1, you wont get correct answer

提交回复
热议问题