在Prolog中尝试执行?

时间:2019-06-07 08:59:07

标签: prolog trie

所以我有一个学校作业,需要我(除其他外)创建一个特里,以便使用它来存储一些数字和每条路径的使用时间。例如,如果我先插入“ 1234”然后再插入“ 1255”,则1和2的节点的值应为2,而3和4的节点的值应为1。

问题是,我不知道如何在Prolog中实现这样的特里(我是一个初学者)。 我找到了这段代码here

:- use_module(library(lists)).
new_trie(root-[]). 

%%% Add a string to the trie. 

% We have reached a word ending, so this must be a terminal node. 
extend_trie([], TrieIn, TrieOut) :- 
        ensure_terminal(TrieIn, TrieOut). 
% If we have a node for C here, we need to extend it with Cs. 
extend_trie([C | Cs], Char-Children, Char-[NewChild | OtherChildren]) :- 
        select(C-CChildren, Children, OtherChildren), 
        !, 
        extend_trie(Cs, C-CChildren, NewChild). 
% There is no C node, so we need to construct a new one. 
extend_trie([C | Cs], Char-Children, Char-[NewChild | Children]) :- 
        extend_trie(Cs, C-[], NewChild). 
% A terminal node is one with the 'terminal' child. 
ensure_terminal(Char-Children, Char-Children) :- 
        member(terminal, Children), 
        !. 
ensure_terminal(Char-Children, Char-[terminal | Children]). 
%%% ---------------------------------------------------------------------- 
%%% Decide whether or not a word occupies the trie. 
%%% ---------------------------------------------------------------------- 
% If we've got to the end of our string, it is a word if there is a terminal child. 
lookup_trie([], _Char-Children) :- 
        member(terminal, Children). 
% If we have more characters in our string, lookup the C trie and continue. 
lookup_trie([C | Cs], _Char-Children) :- 
        member(C-GrandChildren, Children), 
        lookup_trie(Cs, C-GrandChildren). 

但是我不知道如何使用它。我的意思是我不知道如何用这个来创建trie或插入/查找值。

有什么帮助或建议吗?

0 个答案:

没有答案