在单个列表中依次映射多个功能 [英] Mapping multiple functions, in order, over a single list

查看:62
本文介绍了在单个列表中依次映射多个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个列表上依次映射三个不同的函数.为了说明我的意思,假设我们要进行以下三个映射:

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)

如果将mylist定义为'(1 2 3),并且一次运行一个以上函数,则会得到:

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))

您将如何处理?

推荐答案

您可以嵌套两个map以获得所需的效果:

You can nest two maps to achieve the desired effect:

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

在上面的mylist是输入列表,而myfuncs是功能列表.例如,这些列表:

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))

这篇关于在单个列表中依次映射多个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆