调试:无法将预期类型“GHC.Types.Bool”与实际类型“Bool”匹配

mor*_*ron 2 debugging lambda haskell case lambda-calculus

我正在尝试解决 Haskell 的以下练习:

\n

定义函数exists::(N-> Bool)-> N->Bool,它接收谓词 p 和自然数 n,并且如果 O 和 n 之间存在任意数字且 p 为 true,则返回 True。\n示例:

\n
exists pair three = True\nexists isGreaterThanZero O = False\n
Run Code Online (Sandbox Code Playgroud)\n

这段代码位于我的存在函数之前:

\n
{-#LANGUAGE GADTs #-}\n{-# OPTIONS_GHC -fno-warn-tabs #-}\n{-# OPTIONS_GHC -fno-warn-missing-methods #-}\n\nmodule Naturales where\n\nimport Prelude(Show)\n\ndata Bool where {   False :: Bool; \n                    True :: Bool\n                } deriving Show\n\n{- Data Type of Natural Numbers -}\ndata N where { O :: N ; \n               S :: N -> N \n            } deriving Show\n    \n    zero:: N\n    zero= O\n    \n    one:: N\n    one = S O\n    \n    two :: N\n    two = S one \n    \n    three :: N\n    three = S two \n    \n    four :: N\n    four = S three\n    ...\n
Run Code Online (Sandbox Code Playgroud)\n

这就是我对名为“exists”的请求函数进行编程的方式,但是当我尝试编译 .hs 代码时,它\n说

\n
exists:: (N->Bool)->N->Bool\nexists = \\p -> \\x -> case x of {\n            O -> p O;\n            (S y) -> if p (S y) then True else existe p y; {- Line 288 -}\n        }\n\n\n    \xe2\x80\xa2 Couldn't match expected type \xe2\x80\x98GHC.Types.Bool\xe2\x80\x99\n                  with actual type \xe2\x80\x98Bool\xe2\x80\x99\n      NB: \xe2\x80\x98Bool\xe2\x80\x99 is defined at EstudiandoRecursion.hs:(9,1)-(11,47)\n          \xe2\x80\x98GHC.Types.Bool\xe2\x80\x99\n            is defined in \xe2\x80\x98GHC.Types\xe2\x80\x99 in package \xe2\x80\x98ghc-prim-0.5.3\xe2\x80\x99\n    \xe2\x80\xa2 In the expression: p (S y)\n      In the expression: if p (S y) then True else existe p y\n      In a case alternative:\n          (S y) -> if p (S y) then True else existe p y\n    |\n288 |                         (S y) -> if p (S y) then True else existe p y;     | \n
Run Code Online (Sandbox Code Playgroud)\n

我认为我的函数的逻辑存在并且是正确的,但也许我在编写代码时犯了语法错误。

\n

chi*_*chi 5

您重新定义了标准Bool类型。Haskell 不知道您自己重新定义的类型实际上与标准类型相同,因此它将它们视为两种不同的类型:(Bool您的)和GHC.Types.Bool(标准类型)。

if cond then t else e表达式仅适用于标准Bool类型,不适用于您的自定义类型。因此,你不能使用它

if p (S y) then True else exists p y
Run Code Online (Sandbox Code Playgroud)

因为p (S y)返回您自己的自定义Bool。考虑一下

case p (S y) of
   True  -> True
   False -> exists p y
Run Code Online (Sandbox Code Playgroud)

与 不同的是if,它应该可以工作,从新类型中选择正确的构造函数True。如果您喜欢大括号和分号,则False可以使用。case .. of { .. ; ... }