function - 如何用任意数量的函数组成 `not`?

标签 function haskell functional-programming composition

当我有一些类型的功能时

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/

相关文章:

haskell - 带有自定义标记数据类型的 parsec-3.1.0

haskell - 函数的类型类实例

for-loop - F# 嵌套 for 循环中的编译错误,语法冗长

haskell - 什么是单子(monad)?

javascript - 无法调用外部 JavaScript 函数

c - 这个递归函数如何返回正确答案?

javascript - 一个页面上的三个 javascript 函数 - 功能失调

r - 创建一个无需字符串引号即可创建向量的函数

haskell - 为什么将多态函数应用于同一函数内的不同输入时,类型推断会失败

java - 如何给 groovy 闭包参数一个类型