🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.prolog
Article #151

Re: How to get the n'th element of a list

#151
From: Andreas Stolcke
Date: Tue, 07 Apr 1992 18:40
35 lines
1956 bytes
In article <1992Apr7.172958.5219@ugle.unit.no>, baustad@idt.unit.no (Jostein Baustad) writes:
|> I have a Prolog-predicate that gives me the n'th element of a list:
|> 
|> % list_index(List,Index,Element)
|> 
|> list_index([Head|_],1,Head).
|> list_index([_|Tail],Index,Elt) :-
|> 	Index>1,
|> 	NewIndex is Index-1,
|> 	list_index(Tail,NewIndex,Elt).
|> 
|> This works fine for finding the element when the list and the Index are known
|> (instanciated), but I also want to use the same predicate to find the index
|> (that is the first one) when the list and the element are known. My predicate
|> doesn't work because of the 'is'-operator. Of course, I can use two different
|> predicates, but I have a feeling that it is possible with only one predicate
|> and some fine Prolog-code. Any suggestions anyone? Thanks in advance.

Assuming you have version of append/3 and length/2 that do the Right Thing:

list_index(List, N, X) :-
        append(Head, [X| _], List),
        length(Head, N1),
        N is N1 + 1.

I'm not claiming that is the most efficient way to do things -:)

BTW, technically, your constraint "with only one predicate" is of course
vacuous since your can simulate as many predicates as you want in only
one predicate.

-- 
Andreas Stolcke					stolcke@icsi.berkeley.edu
International Computer Science Institute	stolcke@ucbicsi.bitnet
1947 Center St., Suite 600, Berkeley, CA 94704	(510) 642-4274 ext. 126
Technical Details
Message-ID: <rsqauINNbn6@agate.berkeley.edu>
Path: arc1-ca.pugleaf.net!sparky!uunet!spool.mu.edu!agate!ICSI.Berkeley.EDU!stolcke
References: <1992Apr7.172958.5219@ugle.unit.no>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!spool.mu.edu!agate!ICSI.Berkeley.EDU!stolcke
From: stolcke@ICSI.Berkeley.EDU (Andreas Stolcke)
Newsgroups: comp.lang.prolog
Subject: Re: How to get the n'th element of a list
Message-ID: <rsqauINNbn6@agate.berkeley.edu>
Date: 7 Apr 92 18:40:30 GMT
Article-I.D.: agate.rsqauINNbn6
References: <1992Apr7.172958.5219@ugle.unit.no>
Organization: International Computer Science Institute, Berkeley, CA, U.S.A.
Lines: 35
NNTP-Posting-Host: icsib30.icsi.berkeley.edu