【问题标题】:How come my program isn't running and I'm getting Syntax errors? (DrRacket/Scheme)为什么我的程序没有运行并且出现语法错误? (DrRacket/方案)
【发布时间】:2014-09-19 18:50:09
【问题描述】:

我正在尝试编写一个函数,该函数将在数字列表的末尾添加一个新数字,但我似乎无法追踪并纠正我的语法错误。有人可以帮助我吗?谢谢!

(define (add the-list element)
 (cond 
  ((empty? the-list) (list element)         
   (else (cons (first the-list) cons (add (rest the-list) element))))))

(check-expect (four (list 2 5 4) 1) (list 2 5 4 1)) ; four adds num at the end of lon

【问题讨论】:

  • 使用add而不是four调用check-expect

标签: list scheme element racket


【解决方案1】:

有几个放错位置的括号,最后的第二个cons 是错误的,cons 需要 两个 参数。试试这个:

(define (add the-list element) 
  (cond ((empty? the-list) (list element))
        (else (cons (first the-list) 
                    (add (rest the-list) element)))))

使用Racket优秀的编辑器来正确格式化和缩进代码,这样的问题很容易被检测到。提示:使用 Ctrl + i 重新缩进代码,这对于发现语法错误非常有用。附带说明一下,使用现有程序可以更惯用地实现相同的程序,如下所示:

(define (add the-list element) 
  (append the-list (list element)))

或者像这样,使用高阶过程:

(define (add the-list element)
  (foldr cons (list element) the-list))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    相关资源
    最近更新 更多