Prolog Syntax
Syntax
In most languages. there is a rich context-dependent syntax. You
cannot, for example, put a Pascal declaration in an expression.
In Prolog, absolutely everything is a ``term''. Some terms are
interpreted specially in certain contexts, but there is no
context-dependent syntax.
What is a ``term'' really?
A term is tree with named ``holes'' in it.
Prolog has a simple, uniform syntax for writing terms:
functor( arg1, arg2, ... )
Syntactic classes: integer, float, atom (=term with zero arguments),
variable (=named hole).
Examples
one(dead(cat))
one(dead,cat)
one(X)
'an atom with spaces'
+(3.4, zap)
Note: variables and numbers can only appear as leaf nodes;
e.g. X(2) and 1(x) are illegal.
``Syntactic sugar''
Any term can be written in the uniform syntax, but this is not always
very pretty.
E.g. +(*(3,2),4), cons(a,cons(b,cons(c,[])))
( Mind you, Lisp programmers don't complain).
Prolog has special extra syntax for
prefix, infix and postfix operators (3*2+4)
lists ([a,b,c])
character strings ("hello")
term wrapper ( x, y )
Operators
Must declare operators with, e.g. op(700, xfy, then).
700
Operator precedence. High relates to final location in
tree. E.g. + is higher than *
xfx
Operator shape. Picture f as the position of the
operator, and x and y as the positions of the
argument(s). A x argument must be lower precedence; y
arguments can be the same or lower (this gives associativity). We
have: fx and fy (prefix); xfx, xfy and
yfx (infix); and xf, yf (postfix).
then
The name of the operator (an atom).
Lists
Plain old linked lists are widely (over-)used.
Uniform syntax is plain ugly (except to Lisp programmers)
.(a, .(b, .(c, [])))
Instead, can write as
[a, b, c]
Also have Lisp ``dotted pair''
.(a, b)
[a | b ]
More often seen with variable after the `|' (Prolog has better
names for pairs; often `-').
Character lists
Prolog does not have strings.
Prolog does not have chars.
Prolog does not need strings.
Chars are just (packed) integers.
Instead, linked list of integer.
Special syntax for writing:
Term wrapper
We will see this in use later.
{ term }
is equivalent to
{}( term )
I.e. the term is wrapped in {}.
The two-faced comma
Comma (,) is used to separate arguments in the uniform syntax.
Comma is also an operator!
a, b, c
','(a, ','(b, c))
How to tell the difference?
-(a, b)
- (a, b)
The latter is not in the uniform syntax!!!
-( ','(a,b) )
Parenthesis
Used to override operator precedence.
(1 + 2) * 3
*( +(1,2), 3)
Parenthesis must not immediately follow an atom (this would turn it
into uniform syntax)
Atom names
Any identifier that starts with a lower case letter
Any sequence of symbols +-*/<>=` :.?@$&
Semi-colon (`;') or exclamation (`!')
Anything enclosed in single quotes
Writing numbers
Floats, integers as usual
Non-decimal bases use B'alphanumeric;
e.g. 16'31 for 31 (base 16); 2'1111111 for 127.
ASCII use 0'char; e.g. 0'a for 97.