[mercury-users] A suggestion for a tutorial
Peter Schachte
schachte at csse.unimelb.edu.au
Tue Jul 4 10:07:16 AEST 2006
On Mon, Jul 03, 2006 at 03:13:35PM +0200, Nicolas Pelletier wrote:
> Hello again,
>
> as a newbie to Mercury (and not much experienced in logic programming
> either), I find myself making the following error more often than I
> would like ;-)
>
> While writing predicates such as this one:
>
> :- pred square_list(int :: in, int :: in, list(int) :: out) is nondet.
> square_list(N, M, L) :-
> N > 0 -> member(X, 1 .. M), square_list(N - 1, M, L0), L = [X | L0]
> ; L = [].
>
> I often feel the impulse to "over-factorize" the code and write this
> erroneous code instead:
>
> :- pred square_list(int :: in, int :: in, list(int) :: out) is nondet.
> square_list(0, _, []).
> square_list(N, M, L) :-
> member(X, 1 .. M), square_list(N - 1, M, L0), L = [X | L0].
This is a common error in writing Prolog code, too. The key point is
that each clause of a predicate must be a true statement about the
predicate you are defining for all values of the variables in the
head. The second clause is not a true statement when N=0, because it
makes L a non-empty list. The key is to remember that the second
clause of a predicate may apply even if the first one does.
If you prefer the multiple clause notation, you can fix it by adding a
N>0 goal. You might write:
square_list(0, _, []).
square_list(N, M, [X|L]) :-
N>0, member(X, 1 .. M), square_list(N - 1, M, L0).
--
Peter Schachte I do not feel obliged to believe that the same
schachte at cs.mu.OZ.AU God who has endowed us with sense, reason, and
www.cs.mu.oz.au/~schachte/ intellect has intended us to forgo their use.
Phone: +61 3 8344 1338 -- Galileo Galilei
--------------------------------------------------------------------------
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