我正在编写一个程序中的程序,它使用递归来遍历列表,并在计数器达到一定数量N时停在某个指针上
(define (functX N lst)
(define counter 1)
(cond
[(empty? lst) empty]
[(negative? N) empty]
[(< (length lst) N) empty]
[(<= counter N) ((set! counter (+ counter 1))(cons (first lst) (functX N (rest lst)))))]
[else empty]))
我不明白,为什么从底部的第二行给我带来麻烦:我得到的错误是“程序应用程序:预期程序,给定:'(1)(无参数)”
答案 0 :(得分:7)
你把它括在括号中两次。 Scheme中的表达式具有(func-expr arg-expr ...)
形式,因此第一个表达式必须求值为函数。所以,如果你这样做了:
(define (f n) n)
((f 5))
它会评估(f 5)
然后它会尝试评估(5)
这是一个错误。
编辑:一些澄清。
括号中包含以下内容两次:
((set! counter (+ counter 1))(cons (first lst) (functX N (rest lst)))))
首先它评估set!
并减少到(其中n
是一个数字):
(n (cons ...))
然后评估 cons
及其参数(其中x
为结果):
(n x)
然后尝试将参数x
应用于函数n
,但由于n
是一个数字,因此会导致错误。如果您想要进行两次单独的计算并且仅返回值1,则可以使用begin
。
(begin (set! counter (+ counter 1)) (cons (first lst) (functX N (rest lst))))
<强>更新强>
这是一个看起来没有伏都教的事情(因为变异是邪恶的)。
(define (take n xs)
(cond
[(empty? xs) empty]
[(negative? n) empty]
[(eq? n 0) empty]
[else (cons (first xs) (take (- n 1) (rest xs)))]))
答案 1 :(得分:1)
您应该考虑在递归调用中递减N并完全删除counter
变量。