【问题标题】:How to solve this Racket problem using higher order functions?如何使用高阶函数解决这个球拍问题?
【发布时间】: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 map to emulate foldl 在 R5RS 方案中,如果你必须。 :)
  • filter 已经是高阶函数了。

标签: scheme racket primes higher-order-functions sieve


【解决方案1】:

在这种情况下,foldl 是使用正确的工具(foldr 也会给出正确的答案,尽管效率较低,当除数按升序排列时)。这个想法是获取输入列表并在其上重复应用drop-divisible,每个除数列表中的每个元素一次。因为我们在调用之间累积结果,所以最后我们将获得一个由 all 除数过滤的列表。这就是我的意思:

(define (sieve-with divisors lst)
  ; `e` is the current element from the `divisors` list
  ; `acc` is the accumulated result
  (foldl (lambda (e acc) (drop-divisible e acc))
         lst        ; initially, the accumulated result
                    ; is the whole input list
         divisors)) ; iterate over all divisors

我使用lambda 来明确参数名称,但实际上您可以直接传递drop-divisible。我宁愿写这个更短的实现:

(define (sieve-with divisors lst)
  (foldl drop-divisible lst divisors))

无论哪种方式,它都按预期工作:

(sieve-with '(2 3) '(2 3 4 5 6 7 8 9 10))
=> '(2 3 5 7)

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多