【问题标题】:Function expects structure of newtype but not newtype itself函数需要 newtype 的结构,而不是 newtype 本身
【发布时间】:2015-12-05 03:05:02
【问题描述】:

我似乎错过了一些基本的东西。

当我尝试使用 sampleGraph 进行映射连接时,我收到此错误:

Main> map join sampleGraph 

<interactive>:3:10:
    Couldn't match expected type ‘[(Start, [End])]’
            with actual type ‘Graph’
    In the second argument of ‘map’, namely ‘sampleGraph’
    In the expression: map join sampleGraph

这是代码

type Node = Integer
type Edge = (Node,Node)
type Start = Node
type End = Node
newtype Graph = Graph [(Start,[End])] deriving (Eq,Show)

join :: (Start, [End]) -> [Edge]
join (start, ends) = map (\ e -> if start < e then (start, e) else (e, start)) ends

sampleGraph = (Graph
    [(5,[1,2,3]),
     (7,[1,2]),
     (1,[1,2]),
     (2,[1,2])
    ])

【问题讨论】:

    标签: haskell types


    【解决方案1】:

    地图类型是

    map :: (a -> b) -> [a] -> [b]
    

    在这种情况下,连接具有类型

    join :: (Start, [End]) -> [Edge]
    

    所以map join 有类型

    map join :: [(Start, [End])] -> [[Edge]]
    

    我们想要的是Graph -&gt; [[Edge]]。所以我们需要一个函数Graph -&gt; [(Start, [End])],我们就准备好了。幸运的是,使用记录访问器真的很简单!

    type Node = Integer
    type Edge = (Node, Node)
    type Start = Node
    type End = Node
    
    newtype Graph = Graph {
      edges :: [(Start, [End])]
    } deriving (Eq, Show)
    
    join :: (Start, [End]) -> [Edge]
    join (start, ends) = map (\e -> if start < e then (start, e) else (e, start)) ends
    
    sampleGraph =
      Graph [(5, [1, 2, 3]),
             (7, [1, 2]),
             (1, [1, 2]),
             (2, [1, 2])
            ]
    
    foo = map join . edges
    

    我们为边字段声明了一个访问器edges,它自动被赋予了Graph -&gt; (Start, [End])的类型。组合 map join . edges 会产生最终所需的类型。

    另一种方法是使用 case-expression 将 Graph 分解为它的组成部分:

    case sampleGraph of
       Graph edges -> map join edges
    

    生活是多种选择。

    【讨论】:

    • 错字:应该说“我们需要一个函数图 -> [(Start, [End])]”
    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 2012-02-20
    • 2010-09-05
    • 2011-04-04
    • 1970-01-01
    • 2014-10-25
    • 2014-02-15
    • 1970-01-01
    相关资源
    最近更新 更多