[英]Apply a function of two inputs to every element in a list - Haskell
I have a function 我有一个功能
f :: Int -> Int -> Int
and I have a list of arbitrary length but for the sake of the example: 我有一个任意长度的列表,但为了这个例子:
[x1,x2,x3]
I need to apply f to the list such that the resulting list looks like this: 我需要将f应用于列表,使得结果列表如下所示:
[f x1 x1 + f x1 x2 + f x1 x3 , f x2 x1 + f x2 x2 + f x2 x3 , f x3 x1 + f x3 x2 + f x3 x3]
I know that 我知道
map f [x1,x2,x3] will give [f x1, f x2, f x3]
but this doesn't seem like much help here. 但这似乎没有多大帮助。 What's the best way to do it?
最好的方法是什么?
您可以使用列表推导,来说明在ghci下尝试以下表达式,
fun f xs = map sum [[ f x y | y <- xs] | x <- xs]
A solution without list comprehensions: 没有列表推导的解决方案:
Use map
twice. 使用
map
两次。
map (\x -> sum $ map (f x) xs) xs
You can use applicative functors to do it this way : 您可以使用applicative functors以这种方式执行此操作:
import Control.Applicative
let l = ["a", "b", "c"]
(++) <$> l <*> l
That will return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"]
. 这将返回
["aa","ab","ac","ba","bb","bc","ca","cb","cc"]
。
To explain a little bit further, (++) <$> l
will map the function (++)
on every element of l
, thus returning [("a"++), ("b"++), ("c"++)]
. 为了解释得远一点,
(++) <$> l
将映射函数(++)
的每一个元件上l
,从而返回[("a"++), ("b"++), ("c"++)]
。 Then, using <*>
will apply all of these functions to all of the elements of l
. 然后,使用
<*>
将所有这些函数应用于l
所有元素。
See the documentation about applicative functors for more details. 有关更多详细信息,请参阅有关applicative functors的文档。 http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.