【发布时间】:2011-02-15 20:37:29
【问题描述】:
我正在尝试在 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) ->[ (List.filter(fun (this:TrieNode) -> this.Char = c) subnodes).Head ]
member this.AWordEndsHere = match this with | Nil -> false
| SubNodes(c,weh,subnodes) -> weh
module TrieFunctions =
let rec insertWord (wordChars:char list) = function
| Nil -> SubNodes(wordChars.Head, false, [])
| SubNodes(c, weh, subnodes) as node ->
let child = node.GetChild(wordChars.Head)
if child = [] then
SubNodes(wordChars.Head,false,[insertWord wordChars.Tail node])
else
SubNodes(wordChars.Head,false,[insertWord wordChars.Tail child.Head])
type Trie(inner : TrieNode) =
member this.InsertWord(wordChars:char list) = TrieFunctions.insertWord(wordChars)
let trie = Trie(SubNodes(' ',false,List.empty)).InsertWord(['g';'i';'g';'i'])
所以我的问题是:
1. 如何获得对 insertWord 功能的调试访问权限?为什么我现在没有收到?为什么我没有看到错误?
2. 如何让函数 insert word 返回一个 TrieNode 对象列表,这样我就不必将调用括在方括号(“[”,“]”)中。我认为这是一个错误。
3. 欢迎您就在 F# 中实现此数据结构提供任何其他建议。我知道我一定做错了很多事情,因为我对这种语言非常陌生。例如,我知道单词插入功能有缺陷,因为它不检查列表是否为空,因此它过早结束。当我到达那座桥时,我想越过它。
提前谢谢你
提前谢谢你
【问题讨论】:
-
不想在没有确定的情况下进行编辑 - 你的意思是一棵树,对吧?列表和二叉树的扩展?
-
最后的 trie 值最终是类型 (Trie -> Trie) - 这表明它正在部分评估 insertWord
-
前缀树中的树而不是普通树中的树