【问题标题】:Scheme: Error: #<undef> is not a function方案:错误:#<undef> 不是函数
【发布时间】:2017-11-20 15:13:36
【问题描述】:

我是 Scheme 的新手,但我想写的东西似乎很简单。尽管,我缺少一些东西......我有以下定义:

(define (fast-expt x n)
  (if (even? n)
      (expt (expt x (/ n 2)) 2)
      (expt x n)))

它使用了我以前的功能:

(define (expt x n)
  (cond ((= n 0) 1)
        ((= n 1) x)
        ((= n -1) (/ 1 x))
        ((< n 0) (* (/ 1 x) (expt x (+ n 1))))
        (else (* x (expt x (- n 1)))))

函数expt 似乎工作正常,但是当我尝试测试fast-expt 时,它会抛出以下内容:Error: #&lt;undef&gt; is not a function [fast-expt]。如果有关系,我使用在线编译器https://repl.it

【问题讨论】:

    标签: scheme


    【解决方案1】:

    它是works for me,但请注意expt 缺少右括号。也许您需要在在线解释器中在fast-expt 之前定义expt。或者更好的是,切换到一个好的离线解释器,比如 Racket :)。

    另外,fast-expt 的实现必须调用自己,否则它只会对第一个偶数指数起作用,从那时起,它只会使用“慢”expt。应该这样实现:

    (define (square x) (* x x))
    
    (define (fast-expt x n)
       (cond ((zero? n) 1)
             ((even? n) (square (fast-expt x (/ n 2))))
             (else (* x (fast-expt x (- n 1))))))
    

    【讨论】:

    • 是的,我在fast-expt 之前定义了expt,但它仍然对我不起作用。即使复制粘贴代码也不会,所以我真的很困惑。我也会在 DrRacket 编辑器中安装并尝试它,也许它是 repl.it 编译器中的东西。感谢您对 fast-expt 函数的改进:)
    • @barni 我刚刚注意到您的代码缺少右括号,请参阅我更新的答案。而我只是tested it on repl.it,它工作正常。
    • 是的,在 DrRacket 中运行代码,结果还是一样……只是一个括号……真是个愚蠢的错误!非常感谢您的宝贵时间:)
    • 没问题,这是我的荣幸 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2011-11-09
    相关资源
    最近更新 更多