Newsgroups: comp.lang.prolog
Path: cantaloupe.srv.cs.cmu.edu!rochester!cornell!travelers.mail.cornell.edu!news.kei.com!news.mathworks.com!udel!gatech!newsfeed.pitt.edu!uunet!in1.uu.net!newsflash.concordia.ca!news.mcgill.ca!DMI.USherb.CA!clouso.crim.ca!IRO.UMontreal.CA!tarau
From: tarau@IRO.UMontreal.CA (Paul Tarau)
Subject: Re: accessing individual elements of a list?
Message-ID: <D56FJ2.LDx@IRO.UMontreal.CA>
Sender: news@IRO.UMontreal.CA
Organization: Universite de Moncton, Canada
References: <3jjc8j$h8p@gboro.rowan.edu>
Date: Thu, 9 Mar 1995 14:13:49 GMT
Lines: 31

In article <3jjc8j$h8p@gboro.rowan.edu> diamond@elvis.rowan.edu (Sean J. Diamond) writes:
>I'm writing a program to play a game and I have most of it done except I
>can't figure out how to check the value of the nth element of a list.

Well, as usually game writing is too serious to be homework :-), here it is:

nth_member(X,Xs,N):-member_i(X,Xs,1,N).

member_i(X,[X|_],N,N).
member_i(X,[_|Xs],N1,N3):-
  N2 is N1+1,
  member_i(X,Xs,N2,N3).

This one is bidirectional so you can also use it to enumerate
element/position pairs:

?- nth_member(Element,[a,b,c],Position).
Element=a, Position=1;
Element=b, Position=2;
Element=c, Position=3.

For known positions it works as in:

?- nth_member(X,[a,b,c],2).
X=b

and can be made slightly more efficient and much uglier
by inserting a CUT somewhere.


Paul Tarau
