Search code examples
prologfunctor

How to get structure name?


If I have struct_name(a, b, c, d, e)., how can I get the name of the struct? In this case, it would be struct_name.

Is there any specific command to do this or should I transform it in some way in a list (I tried and atom_chars doesn't work) and find save the characters until meeting ( ?


Solution

  • You can use the (=..)/2 predicate (this is an ISO-predicate, so it should work on (almost) all Prolog interpreters) that has on the left side a functor, and on the right side the name of the functor followed by its operands.

    So:

    ?- struct_name(a, b, c, d, e) =.. L.
    L = [struct_name, a, b, c, d, e].
    

    You can thus obtain the name of the struct with:

    get_name(A,N) :-
        A =.. [N|_].
    

    When you then call it with struct_name(a, b, c, d, e), it will give you:

    ?- get_name(struct_name(a, b, c, d, e),N).
    N = struct_name.