user4075334
user4075334

Reputation:

Add elements in a list in Prolog

I want to extract elements from a list and add them into another new list.How can I do this-

L=[['abc',18],['bcd',19],['def',20]],
nth1(Count,L,List1),
nth1(2,List1,Value),
**NOW I WANT TO PUT THIS Valie in another new list.So finally new list will have 
   New=[18,19,20]**

How can I keep adding elements in a new list??

Upvotes: 3

Views: 221

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74177

Assuming your instructor wants you to work out the recursive solution yourself, you could simply say something like this (given your example data):

slurp( []         , []     ) .
slurp( [[_,X]|Xs] , [X|Ys] ) :- slurp(Xs,Ys) .

Upvotes: 1

user1812457
user1812457

Reputation:

The same could be achieved with a maplist:

?- maplist(nth1(2), [['abc',18],['bcd',19],['def',20]], R).
R = [18, 19, 20].

Is the argument order of nth/3 a coincidence?

Upvotes: 2

CapelliC
CapelliC

Reputation: 60004

see findall/3 and friends

?- L=[['abc',18],['bcd',19],['def',20]], findall(E,member([_,E],L), R).
L = [[abc, 18], [bcd, 19], [def, 20]],
R = [18, 19, 20].

Upvotes: 0

Related Questions