F#中的树表示

时间:2011-06-17 20:19:29

标签: f# tree

我正在尝试使用元组列表在F#中实现一个树 [a]其中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'

时,结果类型将是无限的

有没有办法可以做这样的事情,还是不支持像这样的递归元组列表?

2 个答案:

答案 0 :(得分:16)

尝试稍微更改一下数据结构:

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)

答案 1 :(得分:9)

有几种方法可以解决这个问题,丹尼尔很好。但是这里有另一种方式(也使用判别式联合)来定义一个递归数据结构,这个更接近你自己的方法(虽然我认为我可能实际上更喜欢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)