F# F中的树表示#
我正在尝试使用元组列表在F#中实现一个树。F# F中的树表示#,f#,tree,F#,Tree,我正在尝试使用元组列表在F#中实现一个树。 [a]其中a=(字符串,[a]) 每个节点都有其子节点的列表,叶节点将是(名称,[]) 我希望能够像这样递归地遍历列表的每个级别 a b e c d f g 然而,它们并不总是二叉树 let t2 = [("a", [("b", [("c", []), ("d", [])]), ("e", [("f", []), ("g", [])])])] let rec checkstuff tple = match tple w
[a]
其中a
=(字符串,[a])
每个节点都有其子节点的列表,叶节点将是
(名称,[])
我希望能够像这样递归地遍历列表的每个级别
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列表)列表
但是如果有一个
'b列表
当统一'a'
和'b*'a列表'
有没有办法做到这一点,或者不支持这样的元组递归列表?尝试稍微更改一下数据结构:
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)
有两种方法可以解决这个问题,丹尼尔的方法很好。但这里有另一种定义递归数据结构的方法(也使用判别联合),这种方法更接近您自己的方法(尽管我认为我可能更喜欢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)