请注意,这个问题本质上是过程性的,并不像函数式那样直接编写;在这种情况下,编写显式循环比使用
map
或
filter
.
返回两个值很简单,可以通过在递归中传递两个累加器参数并在列表的末尾返回它们来管理。以下是我的实现:
(define (egs pset nset cset hset)
(let loop ((input hset) (output '()) (cset cset))
(if (null? input)
; return modified cset and hset
(list cset output)
(let ((pset-match
(andmap (lambda (p) (my-function (car input) p)) pset))
(nset-match
(ormap (lambda (n) (my-function (car input) n)) nset)))
(cond ((not nset-match)
; if h does not match any members from nset
; remove h from hset, add h to cset
(loop (cdr input) output (cons (car input) cset)))
((not pset-match)
; if h does not match all members of pset
; remove h from hset, leave cset unmodified
(loop (cdr input) output cset))
(else
; otherwise don't remove h from hset, leave cset unmodified
(loop (cdr input) (cons (car input) output) cset)))))))
它使用示例输入:
(define my-function (lambda (x y) (and x y)))
(define hset '(1))
(define pset '(0))
(define nset '(1))
(egs pset nset '() hset)
=> '(() (1))