繁体   English   中英

η减少可能吗?

[英]Is eta reduction possible?

在下面的情况下是否可以应用eta减少?

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

我期待这样的事情是可能的:

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

......但事实并非如此

您的解决方案不起作用,因为(||)适用于Bool值, Data.Char.isLetterData.Char.isSpace的类型为Char -> Bool

pl给你:

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

说明: liftM2(||)提升到(->) r monad,所以它的新类型是(r -> Bool) -> (r -> Bool) -> (r -> Bool)

所以在你的情况下我们会得到:

import Control.Monad
let normalise = filter (liftM2 (||) Data.Char.isLetter Data.Char.isSpace)
import Control.Applicative
let normalise = filter ((||) <$> Data.Char.isLetter <*> Data.Char.isSpace)

值得一看的另一个解决方案是箭头!

import Control.Arrow

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

&&&采用两个函数(实际上是箭头)并将它们的结果拉到一个元组中。 然后,我们只是uncurry || 所以现在是时候了(Bool, Bool) -> Bool ,我们都完成了!

您可以利用Any monoid和monoid实例来返回monoid值的函数:

import Data.Monoid
import Data.Char

let normalise = filter (getAny . ((Any . isLetter) `mappend` (Any . isSpace)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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