Convert list into functor parameter

+2 votes
asked Feb 19, 2011 by anilonwebs

I got stuck to implement a logic. At some instance in my program I have a list say named as List. The length of this List is variable and I don't know in advance. Now I have to pass this list in a functor to create a fact and I am unable to implement it. For eg:

if List is [first] then it should add the fact functor(first).
if List is [first,second] then it should add the fact functor(first,second).
if List is [first,second,third] then it should add the fact functor(first,second,third).
and so on...

I was trying by =.. but here I am unable to map that variable length constraint. For fixed length I am able to perform but I don't know in advance that how many elements will be there in list.

Any suggestions to implement this logic. Thanks.

1 Answer

+5 votes
answered Feb 19, 2011 by felix-dombek

I don't quite understand your problem with =.. but this worked for me:

 assert_list(List) :-
            Term =.. [my_functor|List],

Note that I use my_functor instead of simply functor because functor/3 is a built-in predicate so you cannot assert ternary functor facts (functor(first, second, third)).

Calling it:

 ?- assert_list([first,second,third]).

Checking that it works:

 ?- listing(my_functor).
 :- dynamic user:my_functor/3.

 user:my_functor(first, second, third).


Note that technically, the different n-ary my_functor/n predicates are not the same predicates. You must use different queries in your program for each n. To circumvent this, you could simply assert the list as one and only argument of my_functor:

 ?- List = [first, second, third],

 ?- listing(my_functor).
 :- dynamic user:my_functor/3.

 user:my_functor([first, second, third]).


My SWI-Prolog version is 5.7.5.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter