Reputation:
My aim is to break the given list of lists in such a way that I am able to access the individual lists by the same name. I have the following list:-
mylist([[1,2],[2,3],[3,4],[4,6]]).
I want to break the list into [1,2], [2,3], [3,4], [4,6] so that I can access the items (like [1,2]) individually.
For that, can I create a new fact from the separated list elements? I am able to separate the elements into individual lists. But, I want to convert those individual lists into facts. Like:-
mylist([[1,2],[2,3],[3,4],[4,6]]).
should become the following:-
node([1,2]).
node([2,3]).
node([3,4]).
node([4,6]).
And then I should be able to access each and every list using "node".
Upvotes: 1
Views: 169
Reputation:
The other answer is fine (esp. the forall
solution), but here is what you could do if you knew your list at compile time, and wanted to add the node/1
facts to the database at compile time.
This code is simplified from the example available at the very bottom of this page:
In your file (I will call it nodes.pl):
term_expansion(nodes_list(NL), Nodes) :-
maplist(to_node, NL, Nodes).
to_node(X, node(X)).
nodes_list([[1,2],[2,3],[3,4],[4,6]]).
When I consult the file, I get:
?- [nodes].
true.
?- listing(node).
node([1, 2]).
node([2, 3]).
node([3, 4]).
node([4, 6]).
true.
Two details:
nodes_list/1
, is not going to be in the database.term_expansion/2
must come before the definition of nodes_list/1
in the source file.Upvotes: 1
Reputation: 12972
A great answer (maybe the best) recommended(in the comments) by CapelliC is:
?-forall(member(X,[[1,2],[2,3],[3,4]]),assertz(node(X))).
You could also write:
my_list(L):- member(X,L),assertz(node(X)).
Example:
?- my_list([[1,2],[2,3],[3,4]]).
true ;
true ;
true.
?- node([1,2]).
true ;
false.
Another way thanks to CapelliC's recommendation would be:
?- maplist(X>>assertz(node(X)), [[1,2],[2,3],[3,4]]).
Upvotes: 0