当我有一些类型的功能时
f :: (Ord a) => a -> a -> Bool
f a b = a > b
我想要用 not 包装这个函数的 make 函数。
例如做这样的功能
g :: (Ord a) => a -> a -> Bool
g a b = not $ f a b
我可以使组合器像
n f = (\a -> \b -> not $ f a b)
但我不知道怎么做。
*Main> let n f = (\a -> \b -> not $ f a b)
n :: (t -> t1 -> Bool) -> t -> t1 -> Bool
Main> :t n f
n f :: (Ord t) => t -> t -> Bool
*Main> let g = n f
g :: () -> () -> Bool
我究竟做错了什么?
还有一个额外的问题,我如何用更多和更少的参数来实现这个功能,例如
t -> Bool
t -> t1 -> Bool
t -> t1 -> t2 -> Bool
t -> t1 -> t2 -> t3 -> Bool
最佳答案
实际上,用类型类做任意的 arity 被证明是非常容易的:
module Pred where
class Predicate a where
complement :: a -> a
instance Predicate Bool where
complement = not
instance (Predicate b) => Predicate (a -> b) where
complement f = \a -> complement (f a)
-- if you want to be mysterious, then
-- complement = (complement .)
-- also works
ge :: Ord a => a -> a -> Bool
ge = complement (<)
感谢您指出这个很酷的问题。我爱 haskell 。
关于function - 如何用任意数量的函数组成 `not`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/413930/