需要2个参数,但只找到1个

时间:2019-10-10 15:13:07

标签: racket

我正在做一个实践问题,它要求定义一个函数,该函数应该产生列表loi中的所有元素,可以将其除以3或自然数(多数),但不能同时除以这两者。

下面是我的代码:

(define (keep-multiples-of-three-or loi mult)
  (cond
    [(empty? loi) empty]
    [else (cond [(empty? loi) empty]
                [(and (not (equal? 3 mult)) 
                      (or (equal? (remainder (first loi) 3) 0)
                          (equal? (remainder (first loi) mult) 0)))   
                 (first loi)]           
                [else (keep-multiples-of-three-or (rest-loi) 
                                                  mult)]))]))

(keep-multiples-of-three-or (cons 9 (cons 3 empty)) 3) 错误消息显示:cons expects 2 arguments but found only 1

我不知道这里出了什么问题。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您有几个错误:

  • 无需嵌套cond表达式
  • [(empty? loi) empty]情况重复了两次
  • 不是(rest-loi),而是(rest loi)
  • 在第二种情况下,您需要cons的结果并再次调用递归
  • (not (equal? 3 mult))条件使您的示例返回一个空列表,请仔细考虑:您说mult3,但随后您对其进行了检查mult不是 3

这应该解决问题:

(define (keep-multiples-of-three-or loi mult)
  (cond [(empty? loi) empty]
        [(or (equal? (remainder (first loi) 3) 0)
             (equal? (remainder (first loi) mult) 0))
         (cons (first loi)
               (keep-multiples-of-three-or (rest loi) mult))]
        [else (keep-multiples-of-three-or (rest loi) mult)]))

例如:

(keep-multiples-of-three-or (list 9 3) 3)
=> '(9 3)
(keep-multiples-of-three-or (list 1 3 5 9) 5)
=> '(3 5 9)