next up previous contents
Next: Prolog and Logic Up: Side Effect Programming Previous: ;/2

if ... then & if ... then ... else

Prolog can be made to obey control structures of this form.

The if ... then form makes use of the infix operator ->/2.

The extension to if ... then ... else is achieved with the help of the ;/2 predicate.

You may be comfortable with such constructs but it is usually better if more cumbersome to avoid them. Here is how one might define Prolog's ``if ...then ...else''.



(A -> B ; C) :-

call(A)

!

call(B).

(A -> B ; C) :-

call(C).

There are great dangers in using this construction in conjunction with the cut ( !/0)

Just to illustrate its application we can rewrite the predicate analyse/1 used earlier.



analyse(Term):-

type(Term Type)

( (Type=compound_term ; Type = list) ->

(write(Term Type)

functor(Term N A)

analyse_bit(0 A Term))

;

write(Term Type)). [-5pt]

To repeat it can be very difficult to understand programs using nested ;/2 or the if ... then (... else) construct.

It is almost always preferable to use auxillary predicates to tidy up the `mess'.



analyse(Term):-

type(Term Type)

( non_simple(Type) ->

analyse_non_simple(Term Type)

;

write(Term Type)).

non_simple(compound_term):-

!.

non_simple(list).

analyse_non_simple(Term Type):-

write(Term Type)

functor(Term N A)

analyse_bit(0 A Term). [-5pt]



Paul Brna
Mon May 24 20:14:48 BST 1999