簡體   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