方案中“ if”和“ cond”的差异

问题描述 投票:0回答:1

我正在使用Scheme学习Berkeley CS61A。 pigl函数用于引入递归,示例代码如下

(define (pigl wd)
  (if (pl-done? wd) 
    (word wd 'ay)
    (pigl (word (bf wd) (first wd))) ) )

我试图将if更改为cond表达式,修改后的代码如下

(define (pigl2 wd)
  (cond ((pl-done? wd) (word wd 'ay))
      (else pigl2 (word (bf wd) (first wd))) ) )

[基于我对SICP中ifcond解释的理解,我认为这两个过程应该等效。但是,pigl2不能为输入'ab提供'ba,正确的答案是abay

我不知道我是否误解了ifcond的评估规则,还是犯了其他愚蠢的错误。请帮助我,谢谢!

scheme lisp
1个回答
1
投票

这是您的代码,注释以突出该问题:

(define (pigl2 wd)
  (cond ((pl-done? wd) (word wd 'ay))
      (else
       pigl2 ; this line does nothing at all
       (word (bf wd) (first wd))))) ; return result of calling `word`

您实际上忘记了通话 pigl2:缺少括号!这应该可以解决问题:

(define (pigl2 wd)
  (cond ((pl-done? wd) (word wd 'ay))
        (else (pigl2 (word (bf wd) (first wd))))))
© www.soinside.com 2019 - 2024. All rights reserved.