基本上你正在实现的变体for-each
,这就像map
只是为了副作用:
(define (for-each procedure lst)
(let loop ((lst lst))
(if (null? lst)
'undefined-value
(begin
(procedure (car lst))
(loop (cdr lst))))))
(for-each display (list 1 2 3 4)) ; prints 1234
但是您希望能够将值指定为参数,因此您需要将 lst 更改为 rest 参数:
(define (for-each-arg procedure . lst) ; changed to dotted list / rest here
(let loop ((lst lst))
(if (null? lst)
'undefined-value
(begin
(procedure (car lst))
(loop (cdr lst))))))
(for-each-arg display 1 2 3 4) ; prints 1234
如果您想要更实用的方法,您确实在制作地图或折叠。也许左折叠会更受欢迎:
(define (fold-args join init . lst)
(let loop ((acc init) (lst lst))
(if (null? lst)
acc
(loop (join (car lst) acc) (cdr lst)))))
(fold-args cons '() 1 2 3 4) ; ==> (4 3 2 1)
你实际上可以for-each-arg
用这个来实现:
(define (for-each-arg procedure . lst)
(apply fold-args
(lambda (x acc)
(procedure x)
'undefined)
'undefined
lst))
(for-each-arg display 1 2 3 4) ; => undefined-value; prints 1234