我正在尝试解决以下 Haskell 练习:
定义函数exists::(N->Bool)->N->Bool
,它接收一个谓词p和一个自然数n,如果O和O之间有任意数则返回True n 其中 p 为真。
示例:
exists pair three = True
exists isGreaterThanZero O = False
这段代码在我存在的函数之前:
{-#LANGUAGE GADTs #-}
{-# OPTIONS_GHC -fno-warn-tabs #-}
{-# OPTIONS_GHC -fno-warn-missing-methods #-}
module Naturales where
import Prelude(Show)
data Bool where { False :: Bool;
True :: Bool
} deriving Show
{- Data Type of Natural Numbers -}
data N where { O :: N ;
S :: N -> N
} deriving Show
zero:: N
zero= O
one:: N
one = S O
two :: N
two = S one
three :: N
three = S two
four :: N
four = S three
...
这就是我如何编写所请求的名为 exists 的函数,但是当我尝试编译 .hs 代码时 说
exists:: (N->Bool)->N->Bool
exists = \p -> \x -> case x of {
O -> p O;
(S y) -> if p (S y) then True else existe p y; {- Line 288 -}
}
• Couldn't match expected type ‘GHC.Types.Bool’
with actual type ‘Bool’
NB: ‘Bool’ is defined at EstudiandoRecursion.hs:(9,1)-(11,47)
‘GHC.Types.Bool’
is defined in ‘GHC.Types’ in package ‘ghc-prim-0.5.3’
• In the expression: p (S y)
In the expression: if p (S y) then True else existe p y
In a case alternative:
(S y) -> if p (S y) then True else existe p y
|
288 | (S y) -> if p (S y) then True else existe p y; |
我想我的函数的逻辑是正确的,但也许我在编写代码时犯了语法错误。
最佳答案
您已经重新定义了标准的 Bool
类型。 Haskell 不知道您自己重新定义的类型实际上与标准类型相同,因此它将它们视为两种不同的类型:Bool
(您的)和 GHC.Types.Bool
(标准代码)。
if cond then t else e
表达式仅适用于标准 Bool
类型,不适用于您的自定义类型。因此,您不能在
if p (S y) then True else exists p y
因为 p (S y)
返回您自己的自定义 Bool
。考虑一下
case p (S y) of
True -> True
False -> exists p y
与 if
不同,它应该可以工作,从您的新类型中选择正确的 True
和 False
构造函数。您可以使用 case .. of { .. ; ...
如果您更喜欢大括号和分号。
关于debugging - 调试 : Couldn't match expected type ‘GHC.Types.Bool’ with actual type ‘Bool’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66341296/
相关文章:
c - 如何打印从 C 中的 scanf 输入整数开始递减的奇数?
angular - PrimeNG 报错 ConfirmationService has not b
database - Mongo错误QueryExceededMemoryLimitNoDiskUs
modelica - 如何在创建实例之前在模型中重新声明包?
c++ - 如何在 constexpr if-else 链中导致静态错误?
c++ - CMake 找不到生成的 Visual Studio 15 2017 实例,但可以与 V
reactjs - 如何防止 Nivo 刻度轴文本(条形图)中的文本截断