0

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
  • You are trying to use . to compose map f x, but that is a list, not a function, so it does not compose with .. The error "applied to too few arguments" is due to . returning a function (f . g is the function obtained by composing function f and function g), but the type of total claims to return an Int. So, GHC wonders if the function resulting from . should be applied to some argument which you forgot. This is not the issue in your code, but this is why GHC generated that message. Commented May 3, 2019 at 11:08

1 Answer 1

3

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?)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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