[英]Are these two combinators already available in Haskell?
I need binary combinators of the type 我需要该类型的二进制组合器
(a -> Bool) -> (a -> Bool) -> a -> Bool
or maybe 或许
[a -> Bool] -> a -> Bool
(though this would just be the foldr1 of the first, and I usually only need to combine two boolean functions.) (尽管这只是第一个的foldr1,而且我通常只需要组合两个布尔函数。)
Are these built-in? 这些是内置的吗?
If not, the implementation is simple: 如果不是,则实现很简单:
both f g x = f x && g x
either f g x = f x || g x
or perhaps 也许
allF fs x = foldr (\ f b -> b && f x) True fs
anyF fs x = foldr (\ f b -> b || f x) False fs
Hoogle turns up nothing, but sometimes its search doesn't generalise properly. Hoogle并未显示任何内容,但有时其搜索无法正确概括。 Any idea if these are built-in?
这些是内置的吗? Can they be built from pieces of an existing library?
它们可以从现有库的片段中构建吗?
If these aren't built-in, you might suggest new names, because these names are pretty bad. 如果不是内置名称,则可能会建议使用新名称,因为这些名称非常糟糕。 In fact that's the main reason I hope that they are built-in.
实际上,这就是我希望它们是内置的主要原因。
Control.Monad
defines an instance Monad ((->) r)
, so 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
You could do the same with Control.Applicative.liftA2
. 您可以使用
Control.Applicative.liftA2
进行相同的操作。
Not to seriously suggest it, but... 不认真建议,但是...
ghci> :t (. flip ($)) . flip all (. flip ($)) . flip all :: [a -> Bool] -> a -> Bool ghci> :t (. flip ($)) . flip any (. flip ($)) . flip any :: [a -> Bool] -> a -> Bool
It's not a builtin, but the alternative I prefer is to use type classes to generalize the Boolean operations to predicates of any arity: 它不是内置函数,但是我更喜欢的替代方法是使用类型类将布尔运算泛化为任何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)
I love Haskell! 我爱Haskell!
I don't know builtins, but I like the names you propose. 我不知道内建函数,但我喜欢您提出的名称。
getCoolNumbers = filter $ either even (< 42)
Alternately, one could think of an operator symbol in addition to typeclasses for alternatives. 或者,除了备选的类型类之外,人们还可以想到运算符。
getCoolNumbers = filter $ even <|> (< 42)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.