【发布时间】:2014-10-19 22:18:27
【问题描述】:
我有一个像这样的简单树结构..
type Tree<'a,'b> =
| Node of list<'a * Tree<'a,'b>>
| Leaf of 'b
let phonebook = Node["MyPhonebook",
Node["Work",
Node["Company1", Node["Employee1", Leaf("phone#")];
"Company2", Leaf("phone#")];
"Private",
Node["Family", Node["Brother", Leaf("phone#");]; "Sister", Leaf("phone#")]
]
]
我只是想打印此电话簿的根文件夹(工作、私人),但无论我做什么似乎都无法正确...
let listelements tree =
match tree with
| Node[a, b] -> // OK - root node
printfn "%s" a // OK - root folder name
match b with
//| _ -> printf "%A" b // OK - prints whole node
| Node[a, b] -> printf "%A" a // Match failure!
listelements phonebook
在那之后,我意识到我一直在将元组与列表匹配,所以我尝试了一些不同的方法,但我又遇到了不匹配问题。
let phonebook = [Node["Work",
Node["Company1", Node["Employee1", Leaf("phone#")];
"Company2", Leaf("phone#")];
"Private",
Node["Family", Node["Brother", Leaf("phone#");]; "Sister", Leaf("phone#")]
]
]
let listelements tree =
for i in tree do
match i with
| Node[a, b] -> printf "%s" a // Match fail
let listelements tree =
//tree |> List.iter (fun x -> printf "%A" x) // OK - prints nodes
tree |> List.iter (fun x ->
match x with
| Node[a, b] -> printf "%A" a) // Match fail
我到底做错了什么?必须有一种更优雅、更简单的方法来做到这一点。我来自 C#,这让我发疯:P
【问题讨论】:
标签: f# f#-interactive c#-to-f#