dude123345
dude123345

Reputation: 45

Using a list of pairs as an argument in Prolog

I am trying to find the value per key inputted in Prolog from an associative list. This function works but only for one pair. How can I get it to work for multiple pairs in a list?

  assoc([pair(K,V)],Key,V) :-
     K = Key.
  assoc([pair(K,[])],Key,V):-
     assoc([pair(K,[])],Key,V).

Upvotes: 0

Views: 370

Answers (1)

lurker
lurker

Reputation: 58324

Your simple case, of just one pair in the list, could be written as follows:

assoc([pair(K,V)], K, V).

Your association is a list of such pairs. In Prolog, the simplest way to represent that is with a head-tail form: [H|T] where H is the first element and T is the tail or the rest of the list. In the case of a match, you shouldn't care whether there are any more elements in the list or not. So you should really write the above as:

assoc([pair(K,V)|_], K, V).

In other words, if the key of the first element matches, the value should match (and vice versa). I don't care what the rest of the association list looks like (thus, the _). If they don't, then this clause will fail and Prolog will test the next clause, which should check the rest of the list:

assoc([_|AssocRest], Key, Value) :-
    assoc(AssocRest, Key, Value).

In this case, I don't care what the first pair is (I've taken care of that case already). So the head is _.

A more canonical way to represent a key value pair is with the term Key-Value. So the above would become:

assoc([K-V|_], K, V).
assoc([_|AssocRest], Key, Value) :-
    assoc(AssocRest, Key, Value).

Upvotes: 1

Related Questions