[英]How to use Map with more than one operator
is it possible to use map
with 2 operators in it like map ((*2)+3) [1,2,3,4]
?是否可以使用带有 2 个运算符的map
,例如map ((*2)+3) [1,2,3,4]
? If is yes how?如果是怎么办? i want to make a function that apply (x*2)+3
on a list.我想制作一个在列表上apply (x*2)+3
的 function。
You map
a single function.你map
单 function。 But that function can do whatever you want.但是 function 可以为所欲为。 Your example can be given as an anonymous function for example:您的示例可以作为匿名 function 给出,例如:
map (\n -> n * 2 + 3) [1,2,3,4]
But you can also use function composition, which is likely more readable for a case like this where your function is a case of "do one thing, then the other":但是您也可以使用 function 组合,对于像这样的情况,您的 function 是“做一件事,然后做另一件事”的情况,这可能更具可读性:
map ((+3) . (*2)) [1,2,3,4]
This in turn is equal (by the so-called "functor laws") to这又等于(通过所谓的“函子定律”)
map (+3) . map (*2) $ [1,2,3,4]
Which I personally find a little more readable.我个人觉得这更具可读性。
I think it is easy to first introduce a lambda expression here:我觉得这里先引入一个 lambda 表达式很容易:
map (\x -> (x*2)+3) [1,2,3,4]
This will do exactly what you want.这将完全符合您的要求。 You can perform " function composition " with the (.):: (b -> c) -> (a -> b) -> a -> c
function , and thus write this as:您可以使用(.):: (b -> c) -> (a -> b) -> a -> c
ZC1C425268E68385D14AB5074C17Z执行“ function 组合”,因此将其写为:
map ((+3) . (*2)) [1,2,3,4]
Here you thus can see it as a "chain" of functions, where we pass the input to the rightmost function (here (*2)
), and then the result is passed to the leftmost function (here (+3)
).因此,在这里您可以将其视为函数的“链”,我们将输入传递给最右边的 function(此处为(*2)
),然后将结果传递给最左侧的 function (此处为(+3)
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.