Search code examples
prologkey-valuekeyvaluepair

How to get value from key-value pair in Prolog


I have difficulty finding the way to access values from prolog key-value pairs.

   gas-[2, 3, 1, 1, 3]

Above is an example of my pair, gas is a key, and the list is value. The reason I use this A-B format is because the term -(A, B) denotes the pair of elements A and B. In Prolog, (-)/2 is defined as an infix operator. Therefore, the term can be written equivalently as A-B. from this.

I want to get the list just by 'gas'.


Solution

  • This is done using SWI-Prolog (threaded, 64 bits, version 8.1.24) on Windows 10

    ?- use_module(library(pairs)).
    true.
    

    First an example of constructing the pairs from just a key and value.

    ?- pairs_keys_values(Pairs,[gas],[[2,3,1,1,3]]).
    Pairs = [gas-[2, 3, 1, 1, 3]].
    

    Now that the syntax of what is expected for key-value pairs is known,

    extract a value from a pair given a key.

    ?- pairs_keys_values([gas-[2,3,1,1,3]],[gas],Value).
    Value = [[2, 3, 1, 1, 3]].
    

    EDIT

    After looking into this more perhaps what you want instead is not key-value pairs but Association lists See: library(assoc): Association lists

    ?- list_to_assoc([a-1,b-2,c-3],Assoc),get_assoc(b,Assoc,Value).
    Assoc = t(b, 2, -, t(a, 1, -, t, t), t(c, 3, -, t, t)),
    Value = 2.
    

    Using your example gas-[2,3,1,1,3]

    ?- list_to_assoc([a-1,gas-[2,3,1,1,3],c-3],Assoc),get_assoc(gas,Assoc,Value).
    Assoc = t(c, 3, -, t(a, 1, -, t, t), t(gas, [2, 3, 1, 1, 3], -, t, t)),
    Value = [2, 3, 1, 1, 3].