[英]Is eta reduction possible?
Is it possible to apply eta reduction in below case? 在下面的情况下是否可以应用eta减少?
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 ......但事实并非如此
Your solution doesn't work, because (||)
works on Bool
values, and Data.Char.isLetter
and Data.Char.isSpace
are of type Char -> Bool
. 您的解决方案不起作用,因为
(||)
适用于Bool
值, Data.Char.isLetter
和Data.Char.isSpace
的类型为Char -> Bool
。
$ 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)
. 说明:
liftM2
将(||)
提升到(->) r
monad,所以它的新类型是(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)
import Control.Applicative
let normalise = filter ((||) <$> Data.Char.isLetter <*> Data.Char.isSpace)
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 ||
然后,我们只是uncurry
||
so it's time becomes (Bool, Bool) -> Bool
and we're all done! 所以现在是时候了
(Bool, Bool) -> Bool
,我们都完成了!
You could take advantage of the Any
monoid and the monoid instance for functions returning monoid values: 您可以利用
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.