简体   繁体   English

将两个输入的函数应用于列表中的每个元素 - Haskell

[英]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.

相关问题 当有两个输入时,如何将函数应用于列表的每个元素? 哈斯克尔 - How do I apply a function to each element of list, when it has two inputs? Haskell 如何将 mod 应用于 Haskell 列表中的每个元素 - How to apply mod to every element in a list in Haskell 在列表的每个元素上应用函数 - apply function on every element of a list 在Haskell中是否可以将putStrLn函数应用于字符串列表的每个元素,使其打印到屏幕上,而无需递归 - Is it possible in Haskell to apply the function putStrLn to every element of a list of Strings, have it print to the screen, while being non recursive 在Haskell中,最常见的将函数应用于列表的第N个元素的方法是什么? - In Haskell, what is the most common way to apply a function to every Nth element of a list? 如何将 function 应用于列表的两个元素 - Haskell - How to apply a function to two elements of a list - Haskell Haskell函数用于交换列表中的每个第二个元素 - Haskell function to swap every second element in a list 将函数应用于列表中的每个第二个元素 - Apply a function to every second element in a list 如果 function 用于列表中的每个元素,如何应用? - How to apply if function for every element in a list? Haskell:扫描列表并为每个元素应用不同的函数 - Haskell: Scan Through a List and Apply A Different Function for Each Element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM