Why are compound terms preferable over lists in terms of performance? For example,
matrix(row(1,2,3),row(1,2,3),row(1,2,3))
is preferable over
[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
In Prolog, a compound term of the form is usually pictured as a tree in which every node contains the name of the functor of the term and has exactly children each one of which is the root of the tree of terms .
In Prolog list elements are enclosed by brackets and separated by commas. Another way to represent a list is to use the head/tail notation [H|T]. Here the head of the list, H, is separated from the tail of the list, T, by a vertical bar. The tail of a list is the original list with its first element removed.
You just want the last element of the list. Try this: lastElement([Head]) :- write(Head). lastElement([_|Tail]):- lastElement(Tail).
First, just to be clear: Lists are a kind of compound term.
To see what lists are, use write_canonical/1
. For example, using GNU Prolog:
| ?- write_canonical([1,2,3]).
'.'(1,'.'(2,'.'(3,[])))
Regarding representation in memory, I recommend Richard O'Keefe's book. The details differ between systems, but you can be pretty sure that to represent the term row(1,2,3)
in memory, you need:
For the term .(1, .(2, .(3, [])
in a straight-forward memory representation, you need:
'.'/2
functors[]
).From this, you already see that using lists takes at least roughly twice as much memory in this representation.
A few simple tests that you can carry out yourself will help you to see the difference in memory consumption of these representations for your system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With