简体   繁体   中英

Separate list A/B -> B swi-prolog

I have a List [2/ 4 ,3/ 6 ,1/ 2 ,7/ 5 ] and I want to create a list consisting of only second numbers [ 4 , 6 , 2 , 5 ].

I was thinking something like this:

newlist(L,L2):-
   newlist(L,A/B),
   newlist(A/B,B),
   newlist(B,L2).

That didn't work, any suggestions?

Define a predicate for a single element:

pair_to_2nd(_/B, B).

Now apply this predicate to the list:

?- maplist(pair_to_2nd, [2/4, 3/6, 1/2, 7/5], L).
L = [4, 6, 2, 5].
listDenom([ ],[ ]).
listDenom([_/D|T],[D|V]) :- listDenom(T,V).

Here is a solution using string_to_list .

splitList(A) :-  
    string_to_list(A, [_,_,_,A1,_,_,_,B1,_,_,_,C1,_,_,_,D1,_]),  
    string_to_list(A2, [A1]),  
    string_to_list(B2, [B1]),  
    string_to_list(C2, [C1]),  
    string_to_list(D2, [D1]),  
    write([A2,B2,C2,D2]).

Example:

?- splitList('[2/4,3/6,1/2,7/5]').
[4,6,2,5]
true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM