Search code examples
prologdestructuring

How to deconstruct a compound term in SWI Prolog


I have compound terms that can have a number inside the braces.

For example: qpowieipq(5),lsjdlasa(15) or lkjlk. I got it from the database (like my_list([rxclk,rxer,rxdv,rxd(0),rxd(1),rxd(2),crs,col,txen,txd(0),txd(1),txd(2),‌​txd(3)]).).

How can I get the value of the number inside the braces?

For example:

my_function(qpowieipq(5), X).
X=5.
my_function(lsjdlasa(15), X).
X=15.
my_function(lkjlk, X).
false

I am using SWI Prolog.


Solution

  • You can use (=..)/2 and pattern matching to deconstruct Prolog's compound terms. For instance

    ?- a =.. X.
    X = [a].
    
    ?- a(1) =.. X.
    X = [a, 1].
    

    So, tentatively

    my_function(T, V) :- T =.. [_,V], number(V).
    

    This will work with any ISO compliant Prolog processor.