为什么`let`不能为内部递归过程命名? [英] Why won't `let` work for naming internal recursive procedures?

查看:78
本文介绍了为什么`let`不能为内部递归过程命名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下用于计算阶乘的函数的实现:[1]

Consider the following implementation of a function to compute factorial: [1]

(define fac-tail
  (lambda (n)
    (define fac-tail-helper
      (lambda (n ac)
        (if (= 0 n)
            ac
            (fac-tail-helper (- n 1) (* n ac)))))
    (fac-tail-helper n 1)))

我尝试使用let进行内部定义重写:

I attempted to rewrite using let for the inner define:

(define fac-tail-2
  (lambda (n)
    (let ((fac-tail-helper-2
            (lambda (n ac)
              (if (= 0 n)
                  ac
                  (fac-tail-helper-2 (- n 1) (* n ac))))))
    (fac-tail-helper-2 n 1))))

define时没有错误,但是执行结果为:

There is no error at define time, but execution results in:

#;> (fac-tail-2 4)
Error: undefined variable 'fac-tail-helper-2'.
{warning: printing of stack trace not supported}

如何使let版本正常工作?

方案版本为SISC v 1.16.6

Scheme version is SISC v 1.16.6

[1] 基于SICP 推荐答案

如何使let版本工作?

How can I make the let version work?

使用letrec代替let.

这篇关于为什么`let`不能为内部递归过程命名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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