Search code examples
listdictionaryprologpredicateassociative

Associative Lists in Prolog


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


Solution

  • 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).