Recursing in a lambda function

后端 未结 3 1342
不知归路
不知归路 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 10:00

    You can use Graham's alambda as an alternative to labels:

    (defun fib (n)
      (funcall (alambda (n a b)
                 (cond ((= n 0) 0)
                       ((= n 1) b)
                       (t (self (- n 1) b (+ a b))))) 
               n 0 1)) 
    

    Or... you could look at the problem a bit differently: Use Norvig's defun-memo macro (automatic memoization), and a non-tail-recursive version of fib, to define a fib function that doesn't even need a helper function, more directly expresses the mathematical description of the fib sequence, and (I think) is at least as efficient as the tail recursive version, and after multiple calls, becomes even more efficient than the tail-recursive version.

    (defun-memo fib (n)
      (cond ((= n 0) 0)
            ((= n 1) 1)
            (t (+ (fib (- n 1))
                  (fib (- n 2))))))
    

提交回复
热议问题