【问题标题】:Getting rid of a Graph keyword in Haskell摆脱 Haskell 中的 Graph 关键字
【发布时间】:2013-12-08 01:10:34
【问题描述】:

我有这个数据类型:

data Node a = Node
    { label :: a,
        adjacent :: [(a,Int)] } deriving (Show, Eq)
data Network a = Graph [Node a] deriving (Show, Eq)

我有一个函数可以将 Graph 转换为节点列表:

deGraph :: ([Node a] -> Network a) -> [Node a] -> [Node a]  
deGraph _ x = x
 for example : 
Main> deGraph Graph [ ( Node 'a' [ ( 'b' , 3 ) , ( 'c' ,2 ) ] ) , ( Node 'b' [ ('c' , 3 ) ] ) , ( Node 'c' [] ) ]
[Node {label = 'a', adjacent = [('b',3),('c',2)]},Node {label = 'b', adjacent = [('c',3)]},Node {label = 'c', adjacent = []}]

但是当我在这样的函数中使用函数时:

func1 (Graph x) = deGraph (Graph x)

我收到此错误:

ERROR "./Network.hs":14 - 应用程序中的类型错误 * 表达式:deGraph (Graph x) 术语:图 x 类型:网络 b * 不匹配:[节点 a] -> 网络 a

你能告诉我如何解决这个问题吗?

【问题讨论】:

    标签: haskell


    【解决方案1】:

    您的 deGraph 函数有两个参数,并且只返回两个参数中的第二个。

    你可能想要这个:

    deGraph :: Network a -> [Node a]
    deGraph (Graph x) = x
    

    GHCi 中对deGraph 的调用有效,因为您忘记在Graph 和以下列表周围加上括号,所以它也是一个带有两个参数的调用。在func1 中,您(正确地)使用了括号,但随后出现类型错误,因为您不一致。

    【讨论】:

      【解决方案2】:

      只需将Graph 也设为记录:

      data Network a = Graph { nodes :: [Node a] } deriving (Show, Eq)
      

      那么nodes的类型为Network a -> [Node a],可以这样调用

      Main> nodes $ Graph listOfNodes
      

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 1970-01-01
        • 2010-11-30
        • 2010-10-12
        • 2018-06-17
        • 2022-07-30
        相关资源
        最近更新 更多