2

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'.

repeat
  • 18,496
  • 4
  • 54
  • 166
zxcisnoias
  • 494
  • 3
  • 19
  • Could you provide a MWE? – Emil Vatai Mar 15 '20 at 04:40
  • 2
    Perhaps I'm oversimplifying, but you can just pattern match with unification `Pair = gas-[2, 3, 1, 1, 3], Pair = Key-Values` will bind `Key=gas` and `Values=[2, 3, 1, 1, 3]`. You can also write a predicate as a shortcut `pair_key_values(Key-Values, Key, Values)` and call `pair_key_values(Pair, gas, Values)` where Pair is defined as above. – lambda.xy.x Mar 15 '20 at 14:27

1 Answers1

3

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].
Guy Coder
  • 24,501
  • 8
  • 71
  • 136