>我尝试了很多方法来解决我的作业,但问题是我想我错过了一些东西,或者我以错误的方式使用了某些东西:
我:溶液
(define (return l)
(cond ((null? l) '())
( cond (!= (mod n (car l) 0) )
;; here will check if not equal 0 so it is not
return then I will remove it from the list
((eq? n (car l) )
(return (cdr l)) )
(else (cons (car l) (n (cdr l))))
)
(return n (cdr l) ) ;;if not return then I will keep it in the list
)
解决此问题的标准方法是使用 filter
,因为它已经完成了您想要的操作:
(define (divisibleByN n lst)
(filter (lambda (e) (zero? (modulo e n))) lst))
如果这不是一个可接受的解决方案,我们可以使用标准模板来遍历列表并构建输出列表:
(define (divisibleByN n lst)
; base case: if the list is empty, return the empty list
(cond ((null? lst) '())
; if the current number is divisible by n
((zero? (modulo (car lst) n))
; add it to output list and advance recursion
(cons (car lst) (divisibleByN n (cdr lst))))
; otherwise just advance recursion
(else (divisibleByN n (cdr lst)))))
无论哪种方式,它都可以按预期工作:
(divisibleByN 3 '(5 9 27 14))
=> '(9 27)
(divisibleByN 4 '(15 6))
=> '()
(divisibleByN 7 '())
=> ()
(divisibleByN 5 '(40 40 40 3 10 50))
=> '(40 40 10 50)