【问题标题】:Tree Representation in F#F# 中的树表示
【发布时间】:2011-06-17 20:19:29
【问题描述】:

我正在尝试使用元组列表在 F# 中实现一棵树。
[a] where a = (string, [a])
每个节点都有一个子节点列表,叶子节点是(name, [])

我希望能够像这样递归遍历列表的每一级。

    a
 b     e
c d   f g

然而,它们并不总是二叉树。

let t2 = [("a", [("b", [("c", []), ("d", [])]), ("e", [("f", []), ("g", [])])])]

let rec checkstuff tple =
    match tple with
    | (_, []) -> true
    | (node, children) ->
        List.fold ( || ) false (List.map checkstuff children)

我明白了:

类型不匹配。期待一个
('a * 'b list) list
但给了一个
'b list
统一''a'''b * 'a list' 时生成的类型将是无限的

有没有办法我可以做这样的事情,或者不支持这样的元组递归列表?

【问题讨论】:

    标签: f# tree


    【解决方案1】:

    尝试稍微改变一下你的数据结构:

    type Tree =
      | Branch of string * Tree list
      | Leaf of string
    
    let t2 = Branch ("a", [Branch ("b", [Leaf "c"; Leaf "d"]); Branch ("e", [Leaf "f"; Leaf "g"])])
    
    let rec checkstuff tree =
        match tree with
        | Leaf _ -> true
        | Branch (node, children) ->
            List.fold ( || ) false (List.map checkstuff children)
    

    【讨论】:

      【解决方案2】:

      有几种方法可以解决这个问题,Daniel 的方法很好。但这是另一种定义递归数据结构的方法(也使用判别联合),这种方法更接近您自己的方法(尽管我认为我实际上可能更喜欢 Daniel 的方法,因为案例更明确):

      type tree<'a> =
          | Node of 'a * list<tree<'a>>
      
      let t3 = Node("a", [Node("b", [Node("c",[]); Node("d",[])]); Node("e", [Node("f",[]); Node("g",[])])])
      
      let rec checkstuff tple =
          match tple with
          | Node(_, []) -> true
          | Node(node, children) ->
              List.fold ( || ) false (List.map checkstuff children)
      

      【讨论】:

        猜你喜欢
        • 2015-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多