🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.prolog
Article #46

Re: How to pick elements out of lists?

#46
From: Ken Johnson
Date: Tue, 03 Nov 1992 11:40
75 lines
2098 bytes
In article <1992Oct29.140104.7751@coli.uni-sb.de> ulma@coli.uni-sb.de
(Ulrich Mayring) writes:

%  I have a list and need to recursively pick two elements out of it.  I
%  need every pair of elements in every order, however the order of the
%  pair itself is not important.  It should also be possible to pick an
%  element and the [] as a pair

The following code will do what you want.  The final requirement strikes
me as unusual; could you not extract single elements with member/2
(below) and if none of them suits you, get pairs with the first clause
only of pair/3 (below) ?

I have assumed that you don't want pairs such as (a,a) unless there are
actually two or more `a's in the list. 

Sample invocation

| ?- pair([a,b,c],A,B).

     A=a
     B=b ;

     A=a
     B=c ;

     A=b
     B=a ;

     A=b
     B=c ;

     A=c
     B=a ;

     A=c
     B=b ;

     A=a
     B=[] ;

     A=b
     B=[] ;

     A=c
     B=[] ;
no
| ?-

% ------------------------------------------------------------------------
%  Code: Ken Johnson, November 1992.  You may use and distribute this code
%  freely, but if you sell copies at a profit, I want a share. 

pair(L,A,B) :-
	member(A,L,L1),
	member(B,L1).
pair(L,A,[]) :-
        member(A,L).


member(X,[X|_]).
member(X,[_|T]) :-
	member(X,T).

member(X,[X|T],T).
member(X,[H|T],[H|U]) :-
	member(X,T,U).


-- 
//// Advice to dieters:         ////  Ken Johnson, A I Applications Institute
////   Never eat more than      ////       80 South Bridge, EDINBURGH EH1 1HN
////   you can carry.           ////                 E-mail ken@aiai.ed.ac.uk
////              -- Miss Piggy ////     phone 031-650 2756  fax 031-650 6513
Technical Details
Message-ID: <7829@skye.ed.ac.uk>
Path: arc1-ca.pugleaf.net!sparky!uunet!mcsun!uknet!edcastle!aiai!ken
References: <1992Oct29.140104.7751@coli.uni-sb.de>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!mcsun!uknet!edcastle!aiai!ken
From: ken@aiai.ed.ac.uk (Ken Johnson)
Newsgroups: comp.lang.prolog
Subject: Re: How to pick elements out of lists?
Message-ID: <7829@skye.ed.ac.uk>
Date: 3 Nov 92 11:40:37 GMT
References: <1992Oct29.140104.7751@coli.uni-sb.de>
Followup-To: comp.lang.prolog
Organization: Bugs-R-Us
Lines: 75