Scheme函数,取n和list,返回list n
我尝试了很多方法来解决我的作业,但问题是我想我错过了什么或者我用错了什么方法: 我的: 解决方案Scheme函数,取n和list,返回list n,scheme,Scheme,我尝试了很多方法来解决我的作业,但问题是我想我错过了什么或者我用错了什么方法: 我的: 解决方案 (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)
(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
)
解决此问题的标准方法是使用
过滤器
,因为它已经实现了您想要的功能:
(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)
@hisae如果这篇文章对你有帮助,请不要忘记,只需点击左边的复选标记;)