For Programmers: Free Programming Magazines  


Home > Archive > Prolog > May 2004 > [GNU Prolog] counter









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author [GNU Prolog] counter
gai luron

2004-05-04, 2:59 pm

Hi,
I need to generate unique keys, so I want to use a counter, using
assert/retract predicates. But, what's wrong with my code?

assert(counter(0)).
next_key(X) :-
retract(counter(Y)),
X is Y+1,
assert(counter(X)).

thanks

--
nico

Gregor Rot

2004-05-04, 2:59 pm

gai luron wrote:
> Hi,
> I need to generate unique keys, so I want to use a counter, using
> assert/retract predicates. But, what's wrong with my code?
>
> assert(counter(0)).
> next_key(X) :-
> retract(counter(Y)),
> X is Y+1,
> assert(counter(X)).
>
> thanks
>
> --
> nico
>


use:

next_key :-

you don't need a parameter here...

br,
Greg
Bart Demoen

2004-05-04, 2:59 pm

Gregor Rot wrote:
> gai luron wrote:
>
>
> use:
>
> next_key :-
>
> you don't need a parameter here...
>
> br,
> Greg


Sure he needs the parameter - he is interested in the value of the next key.
What's wrong is the fact

assert(counter(0)).

In any other Prolog system I tried, this seems forbidden, because assert
is a builtin predicate.

In GNU Prolog, you can define it, and assert/1 it is not a builtin:

| ?- assert(foo).
uncaught exception: error(existence_error(procedure,assert/1),top_level/0)

but the fact does not have the desired effect.

You just want to set the counter to 0 initially, right.
There are (at least) three ways to do that:

:- dynamic counter/1.
counter(0).

or by defining:

init_counter :- asserta(counter(0)).
and calling it at some point in your program
(note the use of asserta/1 which GNU knows )

or by putting in you file:

:- asserta(counter(0)).

Note the :- if you don't know what it does, see manual.

Redefine next_key as:

next_key(X) :-
retract(counter(Y)),
X is Y+1,
asserta(counter(X)).

Cheers

Bart Demoen
gai luron

2004-05-04, 2:59 pm

Bart Demoen wrote:

> init_counter :- asserta(counter(0)).
> and calling it at some point in your program
> (note the use of asserta/1 which GNU knows )


Yes! You're right. In my version I was redefining the predicate assert/1...
thanks a lot.
Best.

--
nico

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com