8

タイプのバイナリコンビネータが必要です

(a -> Bool) -> (a -> Bool) -> a -> Bool

または多分

[a -> Bool] -> a -> Bool

(これは最初のfoldr1にすぎませんが、通常は2つのブール関数を組み合わせるだけで済みます。)

これらは組み込みですか?


そうでない場合、実装は簡単です。

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は何も表示しませんが、検索が適切に一般化されない場合があります。これらが組み込まれているかどうかはわかりますか?それらは既存のライブラリの断片から構築できますか?

これらが組み込まれていない場合は、これらの名前がかなり悪いため、新しい名前を提案する可能性があります。実際、それが私がそれらが組み込まれていることを望む主な理由です。

4

3 に答える 3

13

Control.Monadを定義するinstance Monad ((->) r)ので

ghci>:m Control.Monad
ghci>:tliftM2(&&)
liftM2(&&)::(モナドm)=>mブール->mブール->mブール
ghci>liftM2(&&)(5 <)(<10)8
真

で同じことができますControl.Applicative.liftA2


真剣に提案するのではありませんが...

ghci>:t(。flip($))。すべて反転
(。フリップ($))。すべて反転::[a->Bool]-> a-> Bool
ghci>:t(。flip($))。任意のフリップ
(。フリップ($))。いずれかを反転::[a->Bool]-> a-> Bool
于 2010-02-04T18:26:09.410 に答える
6

これは組み込みではありませんが、私が好む代替手段は、型クラスを使用してブール演算を任意のアリティの述語に一般化することです。

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が大好きです!

于 2010-02-05T02:01:57.630 に答える
1

ビルトインはわかりませんが、あなたが提案する名前は好きです。

getCoolNumbers = filter $ either even (< 42)

あるいは、代替の型クラスに加えて、演算子記号を考えることもできます。

getCoolNumbers = filter $ even <|> (< 42)
于 2010-02-04T18:25:58.550 に答える