2

Write a procedure called direct-num-occurs? that checks whether a number occurs in a list of numbers. Examples:

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

This is what I tried:

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

But I'm getting an error that says expected a pair.

4

1 回答 1

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
于 2013-09-16T23:17:22.240 回答