gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:50:20 25 4
gpt4 key购买 nike

当我有一些类型的功能时

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com