Counter in prolog -


i want create counter in prolog.

something starting init/0. adding 1 increment/0, , get_counter/1. value.

but don't know how start if have init/0 no inputs how set 0.

can give me tips how should try this?

i'm not native speaker, if it's not clear mean i'm sorry.

here sort of trying achieve:

?- x0 = 0 /* init */, succ(x0, x1) /* inc */, succ(x1, x2) /* inc */. x0 = 0, x1 = 1, x2 = 2. 

the init giving variable value, incrementing done succ/2, , getval implicit.

however, said in comment, consider use case! if trying keep track of how deep inside loop are, fine succ/2 or following suggestion @mat.

so, count number of foos in list:

list_foos([], 0). list_foos([x|xs], n) :-     (   dif(x, foo)     ->  list_foos(xs, n)     ;   list_foos(xs, n0),         succ(n0, n) % or: n0 + 1 #= n     ). 

you should try out both succ(n0, n) , n0 + 1 #= n see how can use them when either 1 or both of arguments list_foos/2 not ground.

if, however, need maintain global state reason: say, dynamically changing database , need generate increasing integer key table. then, should consider answer @coredump. keep in mind not super easy write code runs on prolog implementation once start using "global" variables. 1 attempt use predicates manipulating database:

:- dynamic foocounter/1.  initfoo :-     retractall(foocounter(_)),     assertz(foocounter(0)).  incrfoo :-     foocounter(v0),     retractall(foocounter(_)),     succ(v0, v),     assertz(foocounter(v)). 

and then, can count global state (it not need in conjunction example use):

?- initfoo. true.  ?- incrfoo. true.  ?- incrfoo. true.  ?- foocounter(v). v = 2. 

this valid code there many pitfalls, use care.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

python - RuntimeWarning: PyOS_InputHook is not available for interactive use of PyGTK -