maximum value of a list 
Author Message
 maximum value of a list

I'm still learning perl so please bear with me
if I've overlooked something obvious.

Is there some simple expression that returns the maximum
value of a list?

I find myself using sort for the purpose, and it
seems kind of overkill, yet it is much easier to use
than an explicit loop.

For example, if I want to print the biggest number
on every row or a file, I can do


but I dislike using sort, which is O(N log N) in time
complexity, when a linear time should suffice.
The obvious alternative is an explicit loop:


but it is longer, needs extra variables and, more important,
cannot be used as an expression unless I turn it into a
function, or can it?

I feel there should be a list operation to pick the maximum,
perhaps using 'map', but it seems quite hard.
The best I've come up with is


Is there an easier way?

(Admittedly any time savings over sort are unlikely to matter
much, this is rather academic interest in learning perl.)

--
Tapani Tarvainen



Mon, 22 Sep 2003 18:11:20 GMT  
 maximum value of a list

Quote:

> Is there some simple expression that returns the maximum
> value of a list?

Not AFAIK.

Quote:
> The obvious alternative is an explicit loop:



Quote:
> but it is longer, needs extra variables and, more important,
> cannot be used as an expression unless I turn it into a
> function, or can it?

You can always do this in Perl: 'do BLOCK' is an expression whose value
is the last evaluated expression in BLOCK:


Note - this isn't a "sub", so don't use "return".

Quote:
> I feel there should be a list operation to pick the maximum,
> perhaps using 'map', but it seems quite hard.
> The best I've come up with is

I find that I've used this, very similar thing:


$result }

Ian



Mon, 22 Sep 2003 20:50:05 GMT  
 maximum value of a list

Quote:

>Is there some simple expression that returns the maximum
>value of a list?

  use List::Util qw/min max/;


Unfortunately, List::Util is not part of the standard distribution for
whatever strange reason, but you can find it at:

  http://search.cpan.org/search?dist=Scalar-List-Utils

--
Ilmari Karonen - http://www.sci.fi/~iltzu/
Please ignore Godzilla / Kira -- do not feed the troll.



Tue, 23 Sep 2003 05:26:02 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. maximum value of a list

2. datetime fields problem on ORACLE

3. Question: optimized method for finding the maximum value in an array

4. Minimum and Maximum of a List

5. Maximum files you can list?

6. list of lists (or non-scalar array values)

7. PERLFUNC: values - return a list of the values in a hash

8. PERLFUNC: values - return a list of the values in a hash

9. Looking for Johan Prins(author of p32)

10. Trapping Referetial Integrity Errors

11. Pardox table transaction ( audit trail ) in Delphi1

12. CRT unit gives divs. by zero error!!!

 

 
Powered by phpBB® Forum Software