I stumbled uppon this question .
The problem was to find how many equal ending digits exist between numbers of the two lists. The answer given seems to be quite efficient using trees to implement something similar to a trie. However playing around with it, I found out that it acts a bit differently than what I would expect: When there are more than one "words" of the second list that have "similarity" with one from the first list, that one is returned only once together with the number of the matching digits of only one of the matching words. Wouldn't it be more correct to return an answer for every match?
I tried to think how this could be done, but I cannot come up with anything good(I'm kind of a beginner in prolog...)
Just for convenience I post the code from gusbro's answer:
same_endings(L1, L2, Endings):-
build_tree(L1, Tree),
maplist(same_ending(Tree), L2, Endings).
same_ending(Tree, N, N-Len):-
atom_chars(N, Digs),
reverse(Digs, RDigs),
same_ending1(RDigs, Tree, 0, Len).
same_ending1([], _, Len, Len).
same_ending1([Dig|Digs], Tree, Len, Len2):-
(select(Dig-SubTree, Tree, _) ->
(succ(Len, Len1), same_ending1(Digs, SubTree, Len1, Len2)) ;
Len2=Len
).
build_tree(L, Tree):-
foldl(add_tree, L, [], Tree).
add_tree(N, Tree, NTree):-
atom_chars(N, Digs),
reverse(Digs, RDigs),
add_tree1(RDigs, Tree, NTree).
add_tree1([], Tree, Tree).
add_tree1([Dig|Digs], Tree, [Dig-SubTree1|Tree1]):-
(select(Dig-SubTree, Tree, Tree1) -> true; SubTree-Tree1=[]-Tree),
add_tree1(Digs, SubTree, SubTree1).
Example :
same_endings([123,223,333],[423,433],Endings).
Endings = [423-2, 433-2].
I would rather expect that a more logical answer would be something like
Endings = [423-2, 423-2, 423-1, 433-1, 433-1, 433-2].