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

Couldn't match expected type with actual type

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

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

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: Couldn't match expected type ‘Graph Point’ with actual type ‘[(Point, [Point])]’ In the pattern: x : xs In an equation for ‘pointNeighbor’: pointNeighbor (x : xs) point = if fst x == point then snd x else pointNeighbor (xs) point

hw1.hs:37:79: Couldn't match expected type ‘Graph Point’ with actual type ‘[(Point, [Point])]’ In the first argument of ‘pointNeighbor’, namely ‘(xs)’ In the expression: pointNeighbor (xs) point

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

提前致谢:)

您的函数要求第一个参数的类型为 Graph。由于定义了 Graph,因此只有一种方法可以做到这一点:使用 Graph 值构造函数(单词 'Graph' 右侧的出现 [= data 定义中 = 的 32=]。

但是,您尝试执行的模式匹配假装第一个参数是普通的 List,而不是已成为 Graph 值构造函数一部分的 List .

模式匹配应该是 (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

另请注意,当列表为空时,您没有定义基本情况。

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

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