Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compound terms and Lists in Prolog

Tags:

prolog

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]]
like image 277
bgarate Avatar asked Apr 24 '16 23:04

bgarate


People also ask

What is a compound term in Prolog?

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 .

How do you get the head and tail of a list in Prolog?

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.

Where is the last element in Prolog?

You just want the last element of the list. Try this: lastElement([Head]) :- write(Head). lastElement([_|Tail]):- lastElement(Tail).


1 Answers

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:

  • one memory cell for the functor/arity
  • 3 memory cells for the arguments

For the term .(1, .(2, .(3, []) in a straight-forward memory representation, you need:

  • 3 memory cells for the three '.'/2 functors
  • 3 memory cells for 1, 2, 3
  • likely some more (such as for []).

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.

like image 186
mat Avatar answered Sep 23 '22 23:09

mat