【发布时间】:2019-02-25 15:28:15
【问题描述】:
我被困在第二季度了。
第一季度。编写一个 drop-divisible 函数,它接受一个数字和一个数字列表,并返回一个新列表,其中仅包含那些不能被该数字“非平凡整除”的数字。
这是我对 Q1 的回答。
(define (drop-divisible x lst)
(cond [(empty? lst) empty]
; if the number in the list is equal to the divisor
; or the number is not divisible, add it to the result list
[(or (= x (first lst))(< 0 (remainder (first lst) x))) (cons (first lst) (drop-divisible x (rest lst)))]
[else (drop-divisible x (rest lst))]))
(module+ test
(check-equal? (drop-divisible 3 (list 2 3 4 5 6 7 8 9 10)) (list 2 3 4 5 7 8 10)))
第二季度。使用 drop-divisible 和(一个或多个)高阶函数 filter、map、foldl、foldr。 (即没有显式递归),编写一个函数,该函数接受一个除数列表、一个要测试的数字列表,并对除数列表的每个元素应用 drop-divisible。这是您的代码应该通过的测试
(module+ test (check-equal? (sieve-with '(2 3) (list 2 3 4 5 6 7 8 9 10)) (list 2 3 5 7)))
我可以想出一个只接受第二个列表的 sn-p,它的工作原理与 Q1 的解决方案相同。
(define (sieve-with divisors lst)
(filter (lambda (x) ((lambda (d)(or (= d x)(< 0 (remainder x d)))) divisors)) lst))
我尝试使用“map”修改 sn-p,但无法使其按预期工作。我也看不出这里可能如何使用“foldr”。
【问题讨论】:
-
问题的关键部分是这样的:“并且应用
drop-divisible...”你在哪里使用它? -
你可以 use
mapto emulatefoldl在 R5RS 方案中,如果你必须。 :) -
filter已经是高阶函数了。
标签: scheme racket primes higher-order-functions sieve