2017-04-02 8 views
-1

私は私の割り当てを解決するために多くの方法を試してみましたが、問題は、私は私が何かを欠場か私は間違った方法で何かを使用推測です:スキーム取りnと、リスト機能、およびリストを返すのn

私: ソリューション

(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 
) 

答えて

1

これを解決するための標準的な方法は、それはすでにあなたが欲しいものを行うよう、filterを使用することです:それは許容ゾルはない場合

(define (divisibleByN n lst) 
    (filter (lambda (e) (zero? (modulo e n))) lst)) 

ution、我々はリストを横断し、出力リストを構築するための標準テンプレートを使用することができます。期待通り

(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) 
+0

@hisaeこの記事はあなたを助けている場合、「ドンください。 [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)を忘れて、その左側のチェックマークをクリックしてください;) –

関連する問題