# [mercury-users] Preferred coding style for switches

Peter Schachte schachte at cs.mu.OZ.AU
Fri Dec 10 15:07:29 AEDT 1999

```On Thu, Dec 09, 1999 at 08:08:00AM -0800, Ralph Becket wrote:
> Say I was writing a predicate that basically implemented a decision table
> comparing two arguments, the first having a type with constructors foo1 ..
> fooM
> and the second having a type with constructors bar1 .. barN.
>
> Is there a preferred style for writing such a predicate, e.g.
>
> p(foo1, bar1) :- ...
> ...
> p(foo1, barN) :- ...
> p(foo2, bar1) :- ...
> ...
> ...
> p(fooM, barN) :- ...
>
> over
>
> p(foo1, X) :-
> 	(
> 		X = bar1,
> 		...
> 	;
> 		X = bar2,
> 		...
> 	;
> 	...
> 	;
> 		X = barN,
> 		...
> 	).
> and so forth?

If the clause bodies are fairly complex and there isn't much
regularity among them that can be exploited to reduce the number of
clauses and simplify the code, it might be best to define a separate
predicate for each body, and write the main predicate in the tabular
(first) form with a single goal in the body of each clause.  If you
line up the arguments and bodies in nice columns, it should be
reasonably easy to read and understand.  If possible, it would be
better to give each of these new predicates a descriptive name, rather
than something like p_foo2_bar3, so that you see something informative
in the "last column" of the table.

Often you can simplify things by calling a few predicates or functions
to compute a bit more data, and then coding the whole decision table
as a bunch of unit clauses.  Eg,

p(X1, X2) :-
determine_something(X1, X2, X3),
determine_something_else(X2, X3, X4),
p_table(X1, X2, X3, X4, yes).

p_table(foo1, bar1, baz1, buz1, yes).
p_table(foo1, bar1, baz1, buz2, no ).
...

> I've just rewritten several predicates from the first style (here N = M = 4
> and not all `bar's need be considered for some `foo's) and, while there is
> less verbiage on the screen thanks to the reduced number of clause heads,
> I'm not convinced that it's any clearer - indeed, the latter style may be
> worse.

In terms of readability, I think it is.  Having it presented in a
nice, tabular form makes it easy to read.  If the tables are fairly
large, it might even be worth the trouble of sorting the clauses just
so the reader can more easily find the case she's interested in.  The
only annoyance is that you have to keep repeating the predicate name
in the first table column.

Of course, if there are too many arguments to fit each clause on a
single line, this whole approach falls apart.

--
Peter Schachte                     Globalisation is beneficial to those who
mailto:schachte at cs.mu.OZ.AU        have. All those who are have-nots are the
http://www.cs.mu.oz.au/~schachte/  victims.
PGP: finger schachte at 128.250.37.3      -- Thomas Kocherry
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au