user840718
user840718

Reputation: 1611

Create two list from facts

I have these facts: fact(1,'a'). fact(2,'b'). fact(3,'c'). fact(4,'d').

my goal is to create 2 lists: one for the ID and one for the strings. So, something like this one: fact(['a', 'b', 'c' , 'd'], [1, 2, 3, 4]). but by a RULE.

Is it possible?

Upvotes: 1

Views: 165

Answers (2)

lurker
lurker

Reputation: 58224

Here's a slightly more involved solution if you don't have the pairs library available (e.g., you're using gprolog):

unzip( [], [], [] ).
unzip( [[L,R]|ListT], [L|LT], [R|RT] ) :-
    unzip( ListT, LT, RT ).

fact_lists( Ids, Atoms ) :-
    findall( [Id, Atom], fact(Id, Atom), FactList ),
    unzip( FactList, Ids, Atoms ).

So you'd call:

fact_lists( Ids, Atoms ).

And get:

Ids = [1,2,3,4]
Atoms = ['a','b','c','d']

Upvotes: 0

CapelliC
CapelliC

Reputation: 60004

the easiest way I know is with library(pairs):

facts_lists(Ids, Atoms) :-
   findall(Id-Atom, fact(Id, Atom), Pairs),
   pairs_keys_values(Pairs, Ids, Atoms).

Upvotes: 1

Related Questions