Scheme 获取数字列表的相同奇偶校验
我正在做基于第一个参数的奇偶性筛选列表的SICP练习。例如:Scheme 获取数字列表的相同奇偶校验,scheme,lisp,sicp,Scheme,Lisp,Sicp,我正在做基于第一个参数的奇偶性筛选列表的SICP练习。例如: (same-parity 1 2 3 4 5 6 7) ; parity of first argument '1' is odd ; and we apply the 'odd' filter to the remaining list, (2 3 4 5 6 7) (1 3 5 7) 这是我想到的,我有点麻烦: ; Helper function (define (list-append lst elem) (if (nu
(same-parity 1 2 3 4 5 6 7)
; parity of first argument '1' is odd
; and we apply the 'odd' filter to the remaining list, (2 3 4 5 6 7)
(1 3 5 7)
这是我想到的,我有点麻烦:
; Helper function
(define (list-append lst elem)
(if (null? lst)
(cons elem nil)
(cons (car lst) (list-append (cdr lst) elem))))
; Actual function
(define (same-parity first . lst)
; start with an empty list, and we'll build it with side-effects
(define L '())
(define (same-parity-inner remaining-lst)
; when the list is exhausted, just return L
(cond ((null? remaining-lst) L)
; if the current element of the list has the same parity
; as the first element, add that to our list
(else (if (= (modulo first 2) (modulo (car remaining-lst) 2))
(list-append L (car remaining-lst)))
; and then recurse with the remaining list elements
(same-parity-inner (cdr remaining-lst)))))
(same-parity-inner lst))
现在我知道在SICP问题上有很多很好的解决方案,但我想知道是否有人能指出我的实现的愚蠢之处,并帮助我找到更好的方法
更新,这里是一个实现,它不是很好,但它是我的第一个工作版本。我发现必须使用“实际列表”而不是vargs函数param有点棘手,所以我编写了另一个内部函数来接受实际列表(也许有更好的方法可以做到这一点?)
有没有一种方法可以在不定义内部函数的情况下递归地执行此操作?您可以使用
apply
进行递归调用,而不使用helper函数。它的最后一个参数是一个列表,它将在函数调用中扩展为参数。这允许您先传递,然后再传递,以及(cdr lst)
您也可以使用cons
从元素和后续列表构建一个新列表,而不是创建一个临时列表来使用append list
(define (same-par first . lst)
(cond ((null? lst) '())
((= (modulo first 2) (modulo (car lst) 2))
(cons (car lst)
(apply same-par first (cdr lst)) ))
(else (apply same-par first (cdr lst)))))
(define (same-par first . lst)
(cond ((null? lst) '())
((= (modulo first 2) (modulo (car lst) 2))
(cons (car lst)
(apply same-par first (cdr lst)) ))
(else (apply same-par first (cdr lst)))))