Why is this an invalid eta conversion?

234 views Asked by At

I am working on a pretty basic problem in haskell. I was trying to count the number of lower case letters in a String. My solution is this

import Data.Char

lowercaseCount :: String -> Int
lowercaseCount x = length $ filter isLower x

I was looking at the actual implementation of lowercaseCount and saw that it seemed like it should have been able to under-go an eta reduction. I tried this

lowercaseCount = length $ filter isLower

but GHC yelled at me saying

Couldn't match expected type [Char] -> Int with actual type Int

I was wondering why this eta reduction is illegal, and if there was a way to make this function able to be in an eta-reduced form.

2

There are 2 answers

1
Carcigenicate On BEST ANSWER

You need to use function composition instead of application. Because you're only partially applying filter, it results in a function.

You need to compose it into length instead of applying it:

lowercaseCount = length . filter isLower
1
chi On
lowercaseCount x = length $ filter isLower x

means

lowercaseCount x = length (filter isLower x)    -- (1)

while

lowercaseCount = length $ filter isLower

means

lowercaseCount = length (filter isLower)

which after eta-expansion becomes

lowercaseCount x = length (filter isLower) x  -- (2)

It should now be evident that (1) and (2) are not equivalent. The latter passes two arguments to length, triggering a type error.