Is eta reduction possible?

2019-02-17 07:02发布

Is it possible to apply eta reduction in below case?

let normalise = filter (\x -> Data.Char.isLetter x || Data.Char.isSpace x )

I was expecting something like this to be possible:

let normalise = filter (Data.Char.isLetter || Data.Char.isSpace)

...but it is not

4条回答
神经病院院长
2楼-- · 2019-02-17 07:40

Your solution doesn't work, because (||) works on Bool values, and Data.Char.isLetter and Data.Char.isSpace are of type Char -> Bool.

pl gives you:

$ pl "f x = a x || b x"
f = liftM2 (||) a b

Explanation: liftM2 lifts (||) to the (->) r monad, so it's new type is (r -> Bool) -> (r -> Bool) -> (r -> Bool).

So in your case we'll get:

import Control.Monad
let normalise = filter (liftM2 (||) Data.Char.isLetter Data.Char.isSpace)
查看更多
该账号已被封号
3楼-- · 2019-02-17 07:43

You could take advantage of the Any monoid and the monoid instance for functions returning monoid values:

import Data.Monoid
import Data.Char

let normalise = filter (getAny . ((Any . isLetter) `mappend` (Any . isSpace)))
查看更多
何必那么认真
4楼-- · 2019-02-17 07:45

Another solution worth looking at involves arrows!

import Control.Arrow

normalize = filter $ uncurry (||) . (isLetter &&& isSpace)

&&& takes two functions (really arrows) and zips together their results into one tuple. We then just uncurry || so it's time becomes (Bool, Bool) -> Bool and we're all done!

查看更多
我只想做你的唯一
5楼-- · 2019-02-17 07:59
import Control.Applicative
let normalise = filter ((||) <$> Data.Char.isLetter <*> Data.Char.isSpace)
查看更多
登录 后发表回答