0

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.

false
  • 10,264
  • 13
  • 101
  • 209

1 Answers1

0

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.

lurker
  • 56,987
  • 9
  • 69
  • 103
  • for sure when possible it's better avoid non logical features, but Prolog' DBs are *very* well tuned for their task, and I would not say are 'inefficient'. On my 2 penny machine I get a fully indexed Wordnet image in about 8 sec... (that's about 300K records...) – CapelliC Apr 08 '14 at 19:00
  • @CapelliC indeed, I tried to qualify my comment with "under certain circumstances" but didn't word it well. – lurker Apr 08 '14 at 19:03