检查数字列表中是否出现数字

时间:2013-09-16 23:14:01

标签: scheme

编写一个名为direct-num-occurs的程序?检查数字列表中是否出现数字。例子:

> (direct-num-occurs? 1 '(2 3 1 4))
;=> #t
> (direct-num-occurs? 1 '(2 3 5 4))
;=> #f

这就是我的尝试:

(define direct-num-occurs?
  (lambda (num ws)
    (cond
      [(null? ws) #f]
      [(equal? num (car ws)) #t]
      [else (direct-num-occurs? (cdr ws) num)])))

但是我收到一个错误,上面写着预期的一对。

1 个答案:

答案 0 :(得分:3)

为了将来参考,您将重新实施member程序:

(define (direct-num-occurs? n lst)
  (if (member n lst) #t #f))

...但我想你是想从头开始写它。显示的实现基本上是正确的,除了你在最后一行以错误的顺序传递了参数。这应该解决它:

(define direct-num-occurs?
  (lambda (num ws)
    (cond
      [(null? ws) #f]
      [(equal? num (car ws)) #t]
      [else (direct-num-occurs? num (cdr ws))])))

当然,它按预期工作:

(direct-num-occurs? 1 '(2 3 1 4))
=> #t

(direct-num-occurs? 1 '(2 3 5 4))
=> #f