简体   繁体   中英

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 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 (\x -> sum $ map (f x) xs) xs

You can use applicative functors to do it this way :

import Control.Applicative
let l = ["a", "b", "c"]
(++) <$> l <*> l

That will return ["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"++)] . Then, using <*> will apply all of these functions to all of the elements of l .

See the documentation about applicative functors for more details. http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM