【问题标题】:Debug: Couldn't match expected type ‘GHC.Types.Bool’ with actual type ‘Bool’调试:无法将预期类型“GHC.Types.Bool”与实际类型“Bool”匹配
【发布时间】:2021-02-23 21:23:09
【问题描述】:

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

定义函数exists::(N-> Bool)-> N->Bool,它接收一个谓词p和一个自然n,如果在O和n之间有任何数字p为真,则返回True。 例子:

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 类型,因此不再引用GHC.Types.BoolBool
  • @WillemVanOnsem,我已经更新了我的问题的描述,添加了我在 exists 函数之前的头代码
  • 好吧,if ... 需要一个内置类型的 Bool,因此您的类型中的 True/False足够。

标签: debugging haskell lambda case lambda-calculus


【解决方案1】:

您重新定义了标准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 不同,它应该可以工作,从您的新类型中选择正确的TrueFalse 构造函数。如果您喜欢大括号和分号,可以使用case .. of { .. ; ... }

【讨论】:

    【解决方案2】:

    您正在使用if … then … else … 表达式。这要求条件是Bool 类型,这是内置 Bool,所以定义你自己的Bool 类型是不够的。

    然而,使用 case … of … 子句就足够了,因此可以在 True/False 数据构造函数上进行模式匹配:

    exists:: (N -> Bool) -> N -> Bool
    exists = \p -> \x -> case x of {
                O -> p O;
                (S y) -> case p (S y) of
                    True -> True
                    _ -> exists p y
            }

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多