Le Kim Trang
Le Kim Trang

Reputation: 459

Prolog: get symbol predicate

I have a symbol table with structure:

key → [value | R]

I would like to write a predicate get_symbol/2, which receives a key (its first parameter) and combines a value (its second parameter) to the first value associated with key in the symbol table.

Can anyone help me with this issue? Thank you very much.

Upvotes: 0

Views: 115

Answers (1)

lurker
lurker

Reputation: 58244

The actual representation of the symbol table has not been described. Let's assume a logical representation which would be a set of facts, sym_table(Key, Value). The symbol table would then be facts:

sym_table(key1, [val1_1, val1_2, ...]).
sym_table(key2, [val2_1, val2_2, ...]).
...

Then your get_symbol/2 predicate, which obtains the first value for a given key, would look like:

get_symbol(Key, Value) :-
    sym_table(Key, [Value | _]).

Note that this predicate will fail, as expected (and I presume desired), if (1) the Key does not exist in the symbol table, or (2) the Key has no values (it is represented as sym_table(Key, []). in the database).

Upvotes: 1

Related Questions