I have the following code, which flattens a tree into a list
tree_list(leaf(Leaf)) --> [Leaf].
tree_list(node1(Leaf, Node)) -->
[Leaf],
tree_list(Node).
tree_list(node2(Leaf, Node1, Node2)) -->
tree_list(Node1),
[Leaf],
tree_list(Node2).
tree_list(node3(_, Node1, Node2, Node3)) -->
tree_list(Node1),
tree_list(Node2),
tree_list(Node3).
Sample query and answer:
?- phrase(tree_list(node3(1,
node1(2, leaf(1)),
node2(3, leaf(1), leaf(1)),
node1(4, leaf(1)))), Ls).
Ls = [2, 1, 1, 3, 1, 4, 1].
I wrote a piece of code which matches to see if two lists have the same list of elements.
treeMatch([], []).
treeMatch([Th| Tt], [Ah| At]) :- Th is Ah, treeMatch(Tt, At).
The above simply goes through a list, checking to see that each index from both lists have the same element till they hit the empty list.
Trying the code with treeMatch([2, 1, 1, 3, 1, 4, 1], [2, 1, 1, 3, 1, 4, 1]) returns true.
But, if I try it with
treeMatch([2, 1, 1, 3, 1, 4, 1], phrase(tree_list(node3(1,
node1(2, leaf(1)),
node2(3, leaf(1), leaf(1)),
node1(4, leaf(1)))), Ls)).
I get false. Is there a way to retrieve the value of Ls and insert it directly to treeMatch to allow it to work?
treeMatchchecking if the lists have the same elements. But usingis/2, you check ifAharithmetically evaluates toTh. ThereforetreeMatch([2], [1+1])will succeed, but neither willtreeMatch(X,foo)nortreeMatch(2,X)(the first because foo is no arithmetic expression and the second because evaluation can only be done on ground terms). Is this the expected behaviour? My suspicion is that you actually want to checkL1 = L2.