🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.prolog
Article #172

was Finding min/max no. from a list

#172
From: Lukanowicz Martin
Date: Fri, 10 Apr 1992 08:44
32 lines
1798 bytes
/*****************************************************************************/
/* finding the minimum and the maximum from a list of numbers */
/* call list_min_max(+ListofNumbers,-TheMinimum,-TheMaximum)  */

list_min_max([Number|RL],Min,Max):-           /* if look at the first      */
     find_min_max(RL,Number,Number,Min,Max).  /* number, it is min and max */

/* (1a) if the list is empty you have the solutions */
find_min_max([],Min,Max,Min,Max).

/* (1b) you must search each number in the list (loop) */
find_min_max([Number|RL],OldMin,OldMax,Min,Max):-
     is_min_or_max(Number,OldMin,OldMax,NewMin,NewMax), /* decision */
     find_min_max(RL,NewMin,NewMax,Min,Max).

/* (2) decision */
/* is the number a new minimum or new maximum? */
is_min_or_max(Number,Min,Max,Number,Max):- Number < Min, !. /* number is min */
is_min_or_max(Number,Min,Max,Min,Number):- Number > Max, !. /* number is max */
is_min_or_max(Number,Min,Max,Min,Max).                      /* nothing       */

/*****************************************************************************/
Benefits of this implementation:

 .) declarative approach
 .) same structure as member/2  (ease to understand)
 .) tailrecursive
 .) 'search-time' increases linear with length of list O(N)
 .) runs in all Prolog implementations as fast as possible with
    as few space (memory) as needed

Martin
Technical Details
Message-ID: <1992Apr10.084401.14400@nestroy.wu-wien.ac.at>
Path: arc1-ca.pugleaf.net!sparky!uunet!email!swdsrv.edvz.univie.ac.at!nestroy!ihss15.wsr.ac.at!luky

Show Full Headers
Complete Article Headers
Newsgroups: comp.lang.prolog
Path: arc1-ca.pugleaf.net!sparky!uunet!email!swdsrv.edvz.univie.ac.at!nestroy!ihss15.wsr.ac.at!luky
From: luky@ihss15.wsr.ac.at (Lukanowicz Martin)
Subject: was Finding min/max no. from a list
Message-ID: <1992Apr10.084401.14400@nestroy.wu-wien.ac.at>
Sender: news@nestroy.wu-wien.ac.at (NetNews)
Organization: Wirtschaftsuniversitaet Wien
Date: Fri, 10 Apr 1992 08:44:01 GMT