I'm new to Prolog and I'm having a hard time using a dynamic predicate.
First, here's the code I'm executing
:- dynamic(list/1).
add(X, LL) :- asserta(list([])), asserta(list(X)), retract(list(LL)).
I know the code looks weird, but I'm simply looking for the right syntax to use.
Now, if I do :
add(2, LL).
Answer will be :
LL = 2 ;
LL = [].
But what I want to do is to add the X (2) INTO the array ([]). So..
LL = [2].
It looks simple (probably is to), but I can't get it work.
Thanks a lot.
If you want to add X
to the front of the list:
add(X, LL) :-
( retract(list(Prev))
-> LL = [X|Prev]
; LL = [X]
),
asserta(list(LL)).
But I agree with @jschimpf's advice. Assert/retract should only be used under certain circumstances as may be quite in efficient in some applications.