Haskell基础课程

Car*_*s00 3 haskell

菜鸟问题,为什么在Haskell中这不正确?

class BasicEq a where
    isEqual :: a -> a -> Bool
    isNotEqual :: a -> a -> Bool
    isNotEqual = not . isEqual
Run Code Online (Sandbox Code Playgroud)

Die*_*Epp 9

让我们打开GHC提示并查看事物的类型:

Prelude> :t not
not :: Bool -> Bool
Prelude> :t (not .)
(not .) :: (a -> Bool) -> a -> Bool
Run Code Online (Sandbox Code Playgroud)

所以你可以看到(not .)需要一个a -> Bool,而不是一个a -> a -> Bool.我们可以将函数组合加倍以获得工作版本:

Prelude> :t ((not .) .)
((not .) .) :: (a -> a1 -> Bool) -> a -> a1 -> Bool
Run Code Online (Sandbox Code Playgroud)

所以正确的定义是:

isNotEqual = (not .) . isEqual
Run Code Online (Sandbox Code Playgroud)

或等效地,

isNotEqual x y = not $ isEqual x y
isNotEqual = curry $ not . uncurry isEqual
Run Code Online (Sandbox Code Playgroud)

等等.


ken*_*ytm 6

.操作者需要两个"一元函数"("× - > Y"),但isEqual是"二进制功能"("× - >ý - > Z"),因此它不会工作.你可以不使用无点形式:

isNotEqual x y = not $ isEqual x y
Run Code Online (Sandbox Code Playgroud)