2

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?

4

3 回答 3

4

You could use a list comprehension, to illustrate try the following expression under ghci,

fun f xs = map sum [[ f x y | y <- xs] |  x <- xs]
于 2013-03-30T10:49:04.863 回答
4

A solution without list comprehensions:

Use map twice.

map (\x -> sum $ map (f x) xs) xs
于 2013-03-30T11:27:13.390 回答
2

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

于 2013-03-30T13:02:41.493 回答