Mapping multiple functions, in order, over a single list [closed]

与世无争的帅哥 提交于 2020-01-11 12:00:15

问题


I would like to map three different functions, in order, over a single list. To demonstrate what I mean, say we want to do the following three mappings:

(map foo mylist)
(map bar mylist)
(map foobar mylist)

If we define mylist as '(1 2 3), and we run the above functions one at a time, we get:

(map foo mylist)     ===>  (foo1 foo2 foo3)
(map bar mylist)     ===>  (bar1 bar2 bar3)
(map foobar mylist)  ===>  (foobar1 foobar2 foobar3)

Instead, I would like the output to be in the following format:

===>  ((foo1 bar1 foobar1) (foo2 bar2 foobar2) (foo3 bar3 foobar3))

How would you go about this?


回答1:


You can nest two maps to achieve the desired effect:

(map (lambda (e)
       (map (lambda (f) (f e))
            myfuncs))
     mylist)

In the above mylist is the input list and myfuncs is the list of functions. For example, these lists:

(define myfuncs (list sqrt square cube))
(define mylist '(1 2 3))

... Will produce this output:

'((1 1 1) (1.4142135623730951 4 8) (1.7320508075688772 9 27))


来源:https://stackoverflow.com/questions/19145726/mapping-multiple-functions-in-order-over-a-single-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!