これらの二つのコンビネータは、Haskellではすでに利用できますか?

StackOverflow https://stackoverflow.com/questions/2202083

  •  18-09-2019
  •  | 
  •  

質問

私は種類のバイナリコンビネータを必要とする

(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は何もターンアップしないが、時にはその検索が適切に一般化されません。任意のアイデアこれらは、内蔵されている場合は?彼らは、既存のライブラリの断片から構築することができますか?

これらは、ビルトインされていない場合はこれらの名前はかなり悪いですので、

、あなたは、新しい名前を提案するかもしれません。実際、私は彼らがをことを願っています主な理由だという。のビルトインされています。

役に立ちましたか?

解決

Control.Monadinstance 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

他のヒント

これは、組み込みではないのですが、私は好む選択肢は、を一般化する型クラスを使用することです 任意のアリティの述語のブール演算:

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)

代わりに、1が代替のための型クラスに加えて、オペレータのシンボルを考えることができます。

getCoolNumbers = filter $ even <|> (< 42)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top