地图!过程应修改现有列表,以将运算符的值应用于原始值。
例如:
(define a '(1 2 3 4 5))
(define double (lambda (x) (* x 2)))
(map! double a)
返回
done
然后当评估a时,应该返回
(2 4 6 8 10)
地图!程序必须这样做。
(define (map! operator given-list)
(if (null? given-list) 'done
(<the procedure that does the modification>)))
我的猜测1:
(map (lambda (x) (set! x (operator x))) given-list)
(map! double a)
返回:
'(#<void> #<void> #<void> #<void> #<void>)
我的猜测2:
(cons (operator (car given-list)) (map! double (cdr given-list)))
(map! double a)
返回:
'(2 4 6 8 10 . done)
我的猜测3:
(set! given-list (map operator given-list))
(map! double a)
返回:
'(2 4 6 8 10)
我的猜测4:
(let ((element (car given-list)))
(set! element (operator given-list) (map! operator (cdr given-list)))
(map! double a)
返回:
'done
但是,当&#34; a&#34; 被评估时,它仍然说:
'(1 2 3 4 5)
我该怎么办??????
答案 0 :(得分:2)
您无法使用set!
。您需要在您正在更改的利弊单元格上使用set-car!
。以下是您的编写方式:
(define (map! f lst)
(let loop ((rest lst))
(unless (null? rest)
(set-car! rest (f (car rest)))
(loop (cdr rest)))))
如果你有SRFI 1,那就更容易了(如果我们暂时忽略了SRFI 1已定义map!
; - )):
(define (map! f lst)
(pair-for-each (lambda (pair)
(set-car! pair (f (car pair))))
lst))