无法将预期类型与实际类型匹配

时间:2015-02-14 21:32:06

标签: haskell

我最近开始学习Haskell,并且无法弄清楚我的代码出了什么问题但最终失败了。

这是我的代码的一部分,显示我已经为Graph类型声明了数据构造函数,它是一个值的元组列表和该值的列表。

data Graph a = Graph [(a,[a])] deriving (Ord, Eq, Show)

这是两个整数的元组的类型同义词,

type Point = (Int, Int)

最后这段代码是使用第一个参数(即搜索/散列值)找到图的第二个参数

pointNeighbor :: Graph Point -> Point -> [Point]
pointNeighbor (x:xs) point = if fst x == point then snd x else pointNeighbor (xs) point

这是我尝试加载模块时收到的错误消息

  

hw1.hs:37:16:       无法匹配预期类型'Graph Point'                   实际类型'[(Point,[Point])]'       在模式中:x:xs       在'pointNeighbor'的等式中:           pointNeighbor(x:xs)指向             = if fst x == point然后snd x else pointNeighbor(xs)point

     

hw1.hs:37:79:       无法匹配预期类型'Graph Point'                   实际类型'[(Point,[Point])]'       在'pointNeighbor'的第一个参数中,即'(xs)'       在表达式中:pointNeighbor(xs)point

似乎Graph Point应该被识别为[(Point,[Point])]但显然它给了我这个错误,我在网上找不到任何解决方案。

提前致谢:)

2 个答案:

答案 0 :(得分:2)

您的函数需要第一个参数为Graph类型。在定义Graph时,只有一种方法可以执行此操作:使用Graph值构造函数(右侧的单词'Graph'的出现 =定义中的data

但是,您试图执行的模式匹配,例如第一个参数是纯List,而不是List构造函数的一部分Graph。 / p>

模式匹配应该是(Graph (x:xs)),并且else子句中的递归调用应该使用(Graph xs),如下所示:

pointNeighbor :: Graph Point -> Point -> [Point]
pointNeighbor (Graph (x:xs)) point = 
    if fst x == point 
        then snd x 
        else pointNeighbor (Graph xs) point

另请注意,当列表为空时,您不能定义基本案例。

答案 1 :(得分:2)

因为Graph是数据构造函数,所以必须对其进行模式匹配:

pointNeighbor :: Graph Point -> Point -> [Point]
pointNeighbor (Graph (x:xs)) point = if fst x == point then snd x else pointNeighbor (Graph xs) point
               ^^^^^                                                                  ^^^^^
相关问题