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

 Page 1 of 1 [ 3 post ]

Relevant Pages