这两个组合器在Haskell中是否已经可用?

Nat*_*ers 8 haskell boolean combinators

我需要这种类型的二元组合器

(a -> Bool) -> (a -> Bool) -> a -> Bool
Run Code Online (Sandbox Code Playgroud)

或者可能

[a -> Bool] -> a -> Bool
Run Code Online (Sandbox Code Playgroud)

(虽然这只是第一个的foldr1,我通常只需要组合两个布尔函数.)

这些是内置的吗?


如果没有,实现很简单:

both f g x = f x && g x
either f g x = f x || g x
Run Code Online (Sandbox Code Playgroud)

也许

allF fs x = foldr (\ f b -> b && f x) True fs
anyF fs x = foldr (\ f b -> b || f x) False fs
Run Code Online (Sandbox Code Playgroud)

Hoogle什么都没有,但有时它的搜索没有正确概括.不知道这些是否是内置的?它们可以用现有的图书馆建造吗?

如果这些不是内置的,您可能会建议使用新名称,因为这些名称非常糟糕.其实这是最主要的原因,我希望他们内置.

eph*_*ent 13

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

  • @ephemient:`fmap和.sequence`? (2认同)

Nor*_*sey 6

它不是内置的,但我更喜欢的替代方法是使用类型类将布尔运算概括为任何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)
Run Code Online (Sandbox Code Playgroud)

我爱哈斯克尔!