在lambda函数中递归 [英] Recursing in a lambda function

查看:124
本文介绍了在lambda函数中递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将以下2个功能合并为一个:

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 (- n 1) b (+ a b))))

我只想拥有一个功能,所以我尝试了如下操作:

I would like to have just one function, so I tried something like this:

(defun fib (n)
  (let ((f0 (lambda (n) (if (= n 0) 0 (funcall f1 n 0 1))))
        (f1 (lambda (a b n) (if (= n 1) b (funcall f1 (- n 1) b (+ a b))))))
    (funcall f0 n)))

但是这不起作用.确切的错误是*** - IF: variable F1 has no value 就LISP而言,我是一个初学者,因此,我希望能对以下问题给出一个清晰的答案:如何在Lisp中编写递归Lambda函数?

however this is not working. The exact error is *** - IF: variable F1 has no value I'm a beginner as far as LISP goes, so I'd appreciate a clear answer to the following question: how do you write a recursive lambda function in lisp?

谢谢.

推荐答案

LET在概念上同时使用相同的封闭环境对变量进行绑定,以评估表达式.请使用 LABELS ,它还会绑定符号f0f1在函数名称空间中:

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)))

这篇关于在lambda函数中递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆