[mercury-users] Preferred coding style for switches

Gustavo A. Ospina gos at info.fundp.ac.be
Fri Dec 10 04:07:31 AEDT 1999


>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?
>

>Any opinions out there?

When I'm starting with Mercury, after some experience in Prolog, I used to
write the clauses in the first style, i.e. unification in the heads of
clauses and several clauses for a switch. That's proper of Prolog programmers.

After discussions with my advisor about such topic, He convinced me that
the second style is more readable and thus more declarative, but it's true
that it's more verbose. I've heard also that the compiler translates the
clausal form of the 1st style into a switch-like form (am I wrong?).

Would be less efficient to rewrite this as follows?

p(Y, X) :-
	(
		X = bar1,
		p_bar1(Y, X)
	;
		X = bar2,
		p_bar2(Y, X)
	;
	...
	;
		X = barN,
		p_barN(Y, X)
	).

Where each p_barI(Y, X) (1 =< I =< N, perhaps X is not required since is
known, X = barI) is

p_barI(Y, X) :-
	(
		Y = foo1,
		...
	;
		Y = foo2,
		...
	;
	...
	;
		Y = barN,
		...
	).

I know this would be tedious, specially the declarations of the new
predicates. My question is if programming like this would be inefficient.

If some bar's are not needed for the foo's, another avantage of switches
could be that it could be rewritten as if-then-else and like this, it could
be easy to program a "default" case for the bar's not used, and maybe make
this deterministic. I think the determinism analysis of Mercury is more
safe when programming with switchs.

Best regards.

+ Gustavo.
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list