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?

2
  • Perhaps you're looking for folds? Commented Mar 30, 2013 at 10:44
  • 1
    appSum = (sum.) . join . liftM2 Commented Mar 30, 2013 at 11:37

3 Answers 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]
Sign up to request clarification or add additional context in comments.

4 Comments

please keep in mind that I do not know the length of the list. 3 is just the example
should be ok, it was to illustrate
Mixing map/filter with list comprehensions makes them both seem more complicated imo. fun f xs = [sum [f x y | y <- xs] | x <-xs] seems clearer.
map by definition map a function over a list and a list comprehension is just a list then It's not so complicated to associate them together. It start to be tricky when we have nested lc into lc. Here we have two level of imbrication starting at three I agree to say that using list comprehension is not a good choice and a fix is needed. Even if I don't find list comprehension really syntactically elegant and a solution as you provided imo is more elegant but hardest to catch at a first glance
4

A solution without list comprehensions:

Use map twice.

map (\x -> sum $ map (f x) xs) xs

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.