这是一个实现:
(define (decrement-alist-values alist keys)
(map (lambda (ass)
(if (member (car ass) keys)
(list (car ass) (- (cadr ass) 1))
ass))
alist))
例子:
> (decrement-alist-values '((1 3) (2 2) (3 3) (4 5) (5 1))
'(1 3 4))
((1 2) (2 2) (3 2) (4 4) (5 1))
Joshua Taylor 提到我的版本在技术上并没有通过突变更新列表。这是一个公平的观点,所以这里是一个变异版本:
(define (decrement-alist-values! alist keys)
(for-each (lambda (ass)
(when (member (car ass) keys)
(set-car! (cdr ass) (- (cadr ass) 1))))
alist))
例子:
> (define a `(,(list 1 3) ,(list 2 2) ,(list 3 3) ,(list 4 5) ,(list 5 1)))
> (decrement-alist-values! a '(1 3 4))
> a
((1 2) (2 2) (3 2) (4 4) (5 1))