Recursing in a lambda function

后端 未结 3 1340
不知归路
不知归路 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条回答
  •  -上瘾入骨i
    2021-02-07 09:52

    LET conceptually binds the variables at the same time, using the same enclosing environment to evaluate the expressions. Use LABELS instead, that also binds the symbols f0 and f1 in the function namespace:

    (defun fib (n)
      (labels ((f0 (n) (if (= n 0) 0 (f1 n 0 1)))
               (f1 (a b n) (if (= n 1) b (f1 (- n 1) b (+ a b)))))
        (f0 n)))
    

提交回复
热议问题