Question

i keep getting this error and i cant work out why

sumSquares a = map (^2) a . foldr (+) 0

Im adding up the squares of a list of numbers.

Was it helpful?

Solution

. is function composition, so what you're saying is, take the function foldr (+) 0 :: [Int] -> Int and compose it with map (^2) a :: [Int], but this makes no sense, your second "function" in this composition isn't really a function.

Would you'd want instead is to swap them and use application, not composition

 foldr (+) 0 (map (^2) a)
 foldr (+) 0 $ map (^2) a

and this can be converted back into composition with what's called "eta conversion"

 sumSquares = foldr (+) 0 . map (^2)
 sumSquares = sum . map (^2)

As an aside, foldr is probably the wrong fold here, foldl' would be more space efficient.

OTHER TIPS

You want to actually do this:

sumSquares a = foldr (+) 0 $ map (^2) a 

Demo in ghci:

ghci> sumSquares [2,2]
8

To solve this problem using (.) operator, you can use the solution as mentioned by @Sassa:

sumSquares = foldr (+) 0 . map (^2)

But I find that hard to read, or you can see the jozefg solution where he uses sum and (.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top