我正在尝试使用一种计算每个节点高度的方法在 F# 中实现一个 trie 结构。
到目前为止,这是我想出的:
type TrieNode =
| SubNodes of char * bool * TrieNode list
| Nil
member this.Char = match this with | Nil -> ' '
| SubNodes(c,weh,subnodes) -> c
member this.GetChild(c:char) = match this with | Nil -> []
| SubNodes(c,weh,subnodes) -> if subnodes.Length > 0 then [ (List.filter(fun (this:TrieNode) -> this.Char = c) subnodes).Head ] else []
member this.AWordEndsHere = match this with | Nil -> false
| SubNodes(c,weh,subnodes) -> weh
module TrieFunctions =
let rec insertWord (wordChars:char list) = function
| Nil -> SubNodes(' ', false, (insertWord wordChars Nil)::[])
//daca aici inca nu e cel putin un nod atunci fa nodul radacina standard adica nodul care nu e sfarsit de cuvant si
//are caracterul ' ' si incepe sa ii construiesti lui subnodurile
| SubNodes(c, weh, subnodes) as node ->
if(wordChars.Length = 1) then
SubNodes(wordChars.Head,true,[])
else
let child = node.GetChild(wordChars.Head)
if child = [] then
SubNodes(wordChars.Head,false,(insertWord wordChars.Tail node)::subnodes )
else
SubNodes(wordChars.Head,false,(insertWord wordChars.Tail child.Head)::subnodes )
let stringToCharList(s:string) = List.ofSeq s
type Trie(inner : TrieNode) =
member this.InsertWord(wordChars:char list) = Trie(TrieFunctions.insertWord wordChars inner)
member this.InsertWord(str:string) = Trie(TrieFunctions.insertWord (TrieFunctions.stringToCharList str) inner)
let trie = Trie(SubNodes(' ',false,List.empty))
.InsertWord("abc")
.InsertWord("abcd")
.InsertWord("abcd")
.InsertWord("abcde")
.InsertWord("abcdef")
.InsertWord("ab123cd")
.InsertWord("abc123d")
.InsertWord("abc132d")
现在我正在尝试编写我的高度计算功能。如果这是一棵二叉树,这将很容易编写,但是在这棵树中,每个节点都有一个子节点列表,所以我不知道如何在 F# 中反复遍历该事物。
这是我到目前为止使用列表折叠操作提出的,但它没有编译:
module NodeFunctions =
let rec nextLevel(node:TrieNode,curlevel:int) = function
| Nil -> curlevel
| SubNodes(_,_,subnodes) ->
List.fold (fun acc (node:TrieNode,_,_) -> let res = nextLevel(node,curlevel+1) and
if( acc > res) then acc else res) curlevel subnodes
有什么想法可以重写此函数以使其工作吗?或者关于如何实现我的目标的任何想法如果这不是正确的想法?
先感谢您