Reputation: 7308
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 typeInt
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.
Upvotes: 2
Views: 243
Reputation: 116139
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.
Upvotes: 9
Reputation: 45741
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
Upvotes: 6