1

my task is to implement maps with lists. We defined associative lists as follows:

[] is the list, k is a key, v is a value and a is an associative list, then [[k, v] | a] is an associative list.

so now ive got to write a predicate, in which it checks if the given argument is a associative list. for example:

?- test([[a,5]]). -> true., ?- test([[1],[2]]). -> false.

im really in despair, i hope someone can help me there

greetings

lurker
  • 56,987
  • 9
  • 69
  • 103
Sleeyz
  • 25
  • 3
  • 1
    Note that a name starting with a lower case letter is not a variable in Prolog. `k`, `v`, and `a` are all atoms. You should probably start with a basic Prolog tutorial. – lurker Apr 28 '18 at 00:41

1 Answers1

2

I may say that associative lists in SWI-Prolog are implemented as an AVL-trees, not as the lists of a dotted pairs, though the latter is possible.

So, let's try your way.

[] is the list, k is a key, v is a value and a is an associative list, then [[k, v] | a] is an associative list.

One correction:

I'd suggest [[ k | v ] | a] that is more compact and is "more associative" )

is_assoc([]).
is_assoc([[K|V] | AL]) :- %corrected 29 apr 2018 19:00 gmt+3
    !, is_assoc( AL ).


put(KV, AL, AL0) :-
   KV = [K|V],
   get(K, AL, V),
   remove(KV, AL, AL_KV),
   put(KV, AL_KV, AL0).

put(KV, AL, [KV | AL]).

get(K, AL, V):-
   member([K|V], AL).
Anton Danilov
  • 1,246
  • 11
  • 26