我正在尝试使用元组列表在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)

我得到:



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

最佳答案

尝试稍微更改数据结构:

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)

关于f# - F#中的树表示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6391334/

10-11 06:12