Straight and simple with dcg!
to_pairs([]) --> [].
to_pairs([X-Ys|XYs]) --> to_pairs_with_key(Ys, X), to_pairs(XYs).
to_pairs_with_key([] , _) --> [].
to_pairs_with_key([V|Vs], K) --> [K-V], to_pairs_with_key(Vs, K).
Sample query:
?- phrase(to_pairs([test1-[usa,france],test2-[germany,china,uk]]), KVs).
KVs = [test1-usa,test1-france,test2-germany,test2-china,test2-uk].
Note that we represent pairs as (-)/2
compounds, which is a wide-spread "best practice". Switching to this particular representation has many benefits:
- Interoperability with many other Prolog library predicates
- Better readability (more concise terms, see example below)
- Increased efficiency
To work with the representation that you used in the questions, just add two maplist/3
goals:
?- use_module(library(lambda)).
true.
?- Xss0 = [[test1,[usa,france]],
[test2,[germany,china,uk]]],
maplist(\[K,Vs]^(K-Vs)^true,Xss0,Xss1),
phrase(to_pairs(Xss1),Ys0),
maplist(\ (K-V)^[K,V]^true,Ys0,Ys1).
Xss0 = [[test1,[usa,france]],[test2,[germany,china,uk]]],
Xss1 = [ test1-[usa,france] , test2-[germany,china,uk] ],
Ys0 = [ test1-usa , test1-france , test2-germany , test2-china , test2-uk ],
Ys1 = [[test1,usa],[test1,france],[test2,germany],[test2,china],[test2,uk]].