[英]Are these two combinators already available in Haskell?
我需要該類型的二進制組合器
(a -> Bool) -> (a -> Bool) -> a -> Bool
或許
[a -> Bool] -> a -> Bool
(盡管這只是第一個的foldr1,而且我通常只需要組合兩個布爾函數。)
這些是內置的嗎?
如果不是,則實現很簡單:
both f g x = f x && g x
either f g x = f x || g x
也許
allF fs x = foldr (\ f b -> b && f x) True fs
anyF fs x = foldr (\ f b -> b || f x) False fs
Hoogle並未顯示任何內容,但有時其搜索無法正確概括。 這些是內置的嗎? 它們可以從現有庫的片段中構建嗎?
如果不是內置名稱,則可能會建議使用新名稱,因為這些名稱非常糟糕。 實際上,這就是我希望它們是內置的主要原因。
Control.Monad
定義instance Monad ((->) r)
,因此
ghci> :m Control.Monad ghci> :t liftM2 (&&) liftM2 (&&) :: (Monad m) => m Bool -> m Bool -> m Bool ghci> liftM2 (&&) (5 <) (< 10) 8 True
您可以使用Control.Applicative.liftA2
進行相同的操作。
不認真建議,但是...
ghci> :t (. flip ($)) . flip all (. flip ($)) . flip all :: [a -> Bool] -> a -> Bool ghci> :t (. flip ($)) . flip any (. flip ($)) . flip any :: [a -> Bool] -> a -> Bool
它不是內置函數,但是我更喜歡的替代方法是使用類型類將布爾運算泛化為任何arity的謂詞:
module Pred2 where
class Predicate a where
complement :: a -> a
disjoin :: a -> a -> a
conjoin :: a -> a -> a
instance Predicate Bool where
complement = not
disjoin = (||)
conjoin = (&&)
instance (Predicate b) => Predicate (a -> b) where
complement = (complement .)
disjoin f g x = f x `disjoin` g x
conjoin f g x = f x `conjoin` g x
-- examples:
ge :: Ord a => a -> a -> Bool
ge = complement (<)
pos = (>0)
nonzero = pos `disjoin` (pos . negate)
zero = complement pos `conjoin` complement (pos . negate)
我愛Haskell!
我不知道內建函數,但我喜歡您提出的名稱。
getCoolNumbers = filter $ either even (< 42)
或者,除了備選的類型類之外,人們還可以想到運算符。
getCoolNumbers = filter $ even <|> (< 42)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.