在Scheme中生成多个列表

时间:2015-09-04 14:48:33

标签: list scheme racket

如果我有一个n个数字的列表,并且想要生成一个新列表,那么这个数字只是同一个列表中任何其他数字的倍数。

例如,对于此列表:'(2 4 5 7 10),结果应为列表'(4 10)

2 个答案:

答案 0 :(得分:4)

如果我们将问题分成几部分会更容易。首先,让我们定义对于我们是多个意味着什么,并编写一个实现我们定义的过程:

(define (is-multiple? num x)
  (and (not (= num x))
       (zero? (modulo num x))))

现在,让我们应用现有的程序来迭代我们的输入并找到答案:

(define (only-multiples lst)
  (filter (lambda (num)
            (ormap (curry is-multiple? num) lst))
          lst))

按预期工作:

(only-multiples '(2 4 5 7 10))
=> '(4 10)

答案 1 :(得分:0)

#lang racket
(require math)

(define numbers '(2 4 5 7 10))

(define (count-divisors-in-numbers n)
  ; count how many numbers d in the list numbers, are a divisor of n.
  (for/sum ([d numbers] #:when (divides? d n)) 1))

(define (multiple-of-other? n)
  ; Note: a number is always a multiplum of it self,
  ;       so only if the count is greater than 1,
  ;       the number is a multiplum of another number
  (> (count-divisors-in-numbers n) 1))

(filter multiple-of-other? numbers)

结果为'(4 10)