也许我的头衔有点乱......
我有这个表格的清单 (定义'((1 3)(2 2)(3 3)(4 5)(5 1)))
我希望减1,这是给定列表中第一个元素的每一对的第二个元素......
例如.. (updateA(1 3 4))
将导致
((1 2)(2 2)(3 2)(4 4)(5 1)
(define (updateA lst)
(for ((x lst))
(for ((y a))
(equal? x (car y)))
;;do something here
))
答案 0 :(得分:1)
这是一个实现:
(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))