我正在使用 R5RS(在球拍中)。这是我的例子
(map (lambda (x) (list (apply + x) (apply * x))) '((1 2 3) (4 5 6)))
-> ((6 6) (15 120))
我只是想知道是否有这样的内置函数
(map-apply '(+ *) '((1 2 3) (4 5 6)))
这可能会产生相同的结果。
没有内置的,但您可以编写自己的:
(define (map-apply funcs items)
(map (lambda (item)
(map (lambda (func)
(apply func item))
funcs))
items))
但是,您必须通过(list + *)
,而不是'(+ *)
。
Are you still there +firegun? If you really, really need to pass the function arguments as '(+ *) then your solution would be:
(define (map-apply function-names items)
(let ((funcs (map (lambda (name) (eval name (interaction-environment))) function-names)))
(map (lambda (item)
(map (lambda (func)
(apply func item))
funcs))
items)))
如果你经常做这些事情,你可以抽象 map-function 的产生。因此其余的将保持不变:
;; Makes a function that applies all functions to an argument
(define (make-map-fun . funs)
(lambda (lis)
(map (lambda (fun) (apply fun lis)) funs)))
(map (make-map-fun + *) '((1 2 3) (4 5 6)))
; ==> ((6 6) (15 120))
;; And you can zip with it too
(apply map
(lambda l ((make-map-fun + *) l))
'((1 2 3) (4 5 6) (7 8 9)))
; ==> ((12 28) (15 80) (18 162))