简体   繁体   中英

Why is this an invalid eta conversion?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM