Dracy Enzo
Dracy Enzo

Reputation: 11

Prolog transformation of arguments into a list

If I had the predicate cat(dog(cow(a,b,c))), how I can transform this into cat(dog(cow([a,b,c])))? I was thinking about the system's predicate =.. but it doesn't end properly, because I obtain cat([dog([cow([a,b,c])])]), and that's not that I want :( The patch needs to fix also other similar case as dog(cat(a,b,c)) into dog(cat([a,b,c])).

Anyone has an idea? Or maybe I'm doing something wrong with the operators...

My idea is:

animal(X) :- atomic(X).
animal(X) :- atomic([]).

cow(X) :-
   animal(X),
   cow([X|List]).

dog(X) :-
   animal(X),
   dog([X|List]).

cat(X) :-
   animal(X),
   cat([X|List]).

Thanks all

Upvotes: 1

Views: 294

Answers (1)

Fred Foo
Fred Foo

Reputation: 363537

Use =.. with a check for ternary functors.

ternary_takes_list(T0, T) :-
    (T0 =.. [F, X, Y, Z] ->
        T =.. [F, [X, Y, Z]]
    ; T0 =.. [F, X0] -> 
        ternary_takes_list(X0, X),
        T =.. [F, X]
    ;
        T = T0
    ).

This works on your examples:

?- ternary_takes_list(cat(dog(cow(a,b,c))), X).
X = cat(dog(cow([a, b, c]))).

?- ternary_takes_list(dog(cat(a,b,c)), X).
X = dog(cat([a, b, c])).

Upvotes: 3

Related Questions