I'm out of my element a bit. I've been using higher order functions and I'm trying to apply a function AND use (.) to combine functions. I'm trying to write a function total that applies the function (first argument) to every element in the list (second argument) and sums the result.

I was given a specific type definition (which I'm not supposed to change) and I'm trying to map the function f to a list and then sum the returned list.

 total :: (Int -> Int) -> [Int] -> Int
 total f x = sum x . map f x

I should get an Int that's the sum of the total. I get an error but it's one I'm unfamiliar with:

* Couldn't match expected type `Int' with actual type `[Int] -> c0'
* Probable cause: `(.)' is applied to too few arguments
  In the expression: sum x . map f
  In an equation for `total': total f x = sum x . map f

I need direction. I don't understand why . should be applied to more arguments.

1 Answers

4
Carcigenicate On Best Solutions

map is fully applied so you shouldn't be using composition here.

Either use the application operator

total f x = sum x $ map f x

Or, if sum didn't require x, you could omit the explicit parameter to the function and use composition instead

total f = sum . map f

The composition operator is expecting a function, but you're fully applying map and passing the operator the list that map returned.

(I'm unfamiliar with a sum function that would accept an int though along with a list. Is that an error as well?)