首页 > 解决方案 > Haskell 类型错误 - 无法将预期类型“a”与实际类型“RE a”匹配

问题描述

所以我有以下几行......

firstMatches :: RE a -> [a] 
firstMatches (a :+: b)
    | (matchEmpty a == True) = [a]

其中 matchEmpty 定义为...

matchEmpty :: RE a -> Bool

matchEmpty Empty =  True
matchEmpty (a :+: b)
    | matchEmpty a == False = False
    | matchEmpty b == False = False
    | otherwise = True

我收到错误“无法将预期类型‘a’与实际类型‘RE a’匹配”

我很确定我只是没有为 matchEmpty 提供正确的论点,但我不知道该怎么做

matchEmpty a == False = False

RE 定义为

data RE a            -- regular expressions over an alphabet defined by 'a'
= Empty          -- empty regular expression
| Sym a          -- match the given symbol
| RE a :+: RE a  -- concatenation of two regular expressions
| RE a :|: RE a  -- choice between two regular expressions
| Rep (RE a)     -- zero or more repetitions of a regular expression
| Rep1 (RE a)    -- one or more repetitions of a regular expression
deriving (Show)

标签: haskell

解决方案


你的第一个代码块有两个东西叫做a. 在这里,我替换了变量以避免重复:

firstMatches :: RE r -> [r] 
firstMatches (a :+: b)
    | (matchEmpty a == True) = [a]

在错误消息中进行相同的替换:

无法将预期类型“r”与实际类型 [r] 匹配。'r' 是一个刚性类型变量,由 firstMatches :: RE r -> [r] 的类型签名绑定

你有a :: Re r,并构造[a] :: [RE r]。但是类型签名说firstMatches返回[r]

  1. 也许您的实现是正确的,并且您打算使用 `firstMatches :: RE r -> [RE r]
  2. 也许您的类型签名是正确的。使 RHS 匹配类型 sig 的一种方法是| (matchEmpty a == True) = []. 这个总是返回空列表的函数不是很有用,但是r我们可以使用范围内没有类型的值。你有其他函数可以接受RE r并返回一个r吗?应该firstMatches得到另一个论点?

推荐阅读