首页 > 解决方案 > 球拍:预期:程序?

问题描述

我有以下代码:

(define numbers '(2 3 5 3 1 22 2))

(define (count val l) 
    (if (null? l)
        0
        (+
            (if (= (first l) val) 1 0)
            (count val (rest l))   
        )
    )
)

(display (count 6 numbers))

(对不起,如果我的代码看起来很糟糕,只需要使用这种语言一次)

编译器说:

count: contract violation
  expected: procedure?
  given: 6
  argument position: 1st
  other arguments...:
   '(3 5 3 1 22 2)

标签: functionruntime-errorschemeracketcontract

解决方案


您正在交互区域中输入代码。

不。在源代码区输入,然后加载。然后它工作。

发生的情况是,该功能count已经存在,而您正在重新定义它。但是如果你在交互区域这样做,你的新函数将使用已经存在的函数,而不是递归地调用自己,因为它应该:

(define (count val l) 
    (if (null? l)
        0
        (+
            (if (= (first l) val) 1 0)
            (count val (rest l))       ;; ****** HERE
        )
    )
)

现有函数需要一个过程作为其第一个参数,如其文档中所示。


推荐阅读