Greatest element of a list

From Rosetta Code
Task
Greatest element of a list
You are encouraged to solve this task according to the task description, using any language you may know.

Create a function that returns the maximum value in a provided set of values, where the number of values isn't known until runtime.

Ada

The keys for this task are initializing the compared value to the 'First value of the element type, and use of an unconstrained array type. <ada> with Ada.Text_Io;

procedure Max_Test is

  -- substitute any array type with a scalar element
  type Flt_Array is array (Natural range <>) of Float;
  
  -- Create an exception for the case of an empty array
  Empty_Array : Exception;
  
  function Max(Item : Flt_Array) return Float is
     Max_Element : Float := Float'First;
  begin
     if Item'Length = 0 then 
        raise Empty_Array;
     end if;
 
     for I in Item'range loop
        if Item(I) > Max_Element then
           Max_Element := Item(I);
        end if;
     end loop;
     return Max_Element;
  end Max;
   
  Buf : Flt_Array := (-275.0, -111.19, 0.0, -1234568.0, 3.14159, -3.14159);

begin

  Ada.Text_IO.Put_Line(Float'Image(Max(Buf)));

end Max_Test;</ada> A generic function Max to deal with any floating-point type. <Ada> generic

  type Item is digits <>;
  type Items_Array is array (Positive range <>) of Item;

function Generic_Max (List : Items_Array) return Item; </Ada> Implementation of: <Ada> function Generic_Max (List : Items_Array) return Item is

  Result : Item := List (List'First);

begin

  for Index in List'First + 1..List'Last loop
     Result := Item'Max (Result, List (Index));
  end loop;
  return Result;

end Generic_Max; </Ada> When the argument array is empty, Constraint_Error exception is propagated, because array indexing is checked in Ada. Note also use of the floating-type attribute Max.

C

This works well with floats. Replace with double, int or what-have-you before passing a different data type. <C>#include <assert.h>

float max(unsigned int count, float values[]) {

    float themax;
    unsigned int idx;
    assert(count > 0);
    themax = values[0];
    for(unsigned int idx = 1; idx < count; ++idx) {
         themax = values[idx] > themax ? values[idx] : themax;
    }
    return themax;

}</C>

C++

This will work for any type with a < operator defined. Uses the standard library function max_element(). <cpp>#include <algorithm>

  1. include <cassert>

template<typename Ty> Ty max(unsigned int count, Ty values[]) {

    assert(count > 0);
    return *std::max_element(values, values + count);

}</cpp>

Common Lisp

The built-in Common Lisp function max takes the max of all its arguments. <lisp>(max 1 2 3 4) (reduce #'max values) ; find max of a list (loop for x in values

     maximize x) ; alternative way to find max of a list</lisp>

Erlang

From here

list_max([Head|Rest]) ->
  list_max(Rest, Head).

list_max([], Res) -> Res;
list_max([Head|Rest], Max)
   when Head > Max
       -> list_max(Rest, Head);
list_max([_Head|Rest], Max)  -> list_max(Rest, Max).

Using it.

>list_max([9,4,3,8,5]).
9

Forth

: array-max ( addr len -- max )
  dup 0= if nip exit then
  over @  rot cell+  rot 1-
  cells bounds ?do  i @ max  cell +loop ;
: stack-max ( n ... m count -- max ) 1 ?do max loop ;

Haskell

The built-in Haskell function maximum already does this.

my_max = maximum

It can alternately be defined as a "fold" on the built-in two-argument max function.

my_max = foldl1 max

J

Verb maxatom returns the maximum value among atoms (smallest indivisible components) of the input, without regard to the shape of the input. The output of verb maxitem has the shape of an item of the input, and the value of each atom is the maximum along the largest axis. For a list of scalars these are equivalent.

maxatom=: >./ @ ,
maxitem=: >./

Java

The first function works with arrays of floats. Replace with arrays of double, int, or other primitive data type. <java>public static float max(float[] values) throws NoSuchElementException {

   if (values.length == 0)
       throw new NoSuchElementException();
   float themax = values[0];
   for (int idx = 1; idx < values.length; ++idx) {
       if (values[idx] < themax)
           themax = values[idx];
   }
   return themax;

}</java>

Optionally, if it is OK to rearrange the contents of the original array: <java>public static float max(float[] values) throws NoSuchElementException {

   if (values.length == 0)
       throw new NoSuchElementException();
   Arrays.sort(values);//sorts the values in ascending order
   return values[values.length-1];

}</java>

The following functions work with arrays or Lists of reference types, respectively. Note that the type is required to implement Comparable, to ensure we can compare them. For Lists, there is a utility method Collections.max() that already does this. <java>public static <T extends Comparable<? super T>> T max(T[] values) throws NoSuchElementException {

   if (values.length == 0)
       throw new NoSuchElementException();
   T themax = values[0];
   for (int idx = 1; idx < values.length; ++idx) {
       if (values[idx].compareTo(themax) > 0)
           themax = values[idx];
   }
   return themax;

}

import java.util.List; import java.util.Collections;

public static <T extends Comparable<? super T>> T max(List<T> values) {

   return Collections.max(values);

}</java>

Works with: UCB Logo

If the template is, like SUM, the name of a procedure that is capable of accepting arbitrarily many inputs, it is more efficient to use APPLY instead of REDUCE. The latter is good for associative procedures that have been written to accept exactly two inputs:

to max :a :b
output ifelse :a > :b [:a] [:b]
end
print reduce "max [...]

Alternatively, REDUCE can be used to write MAX as a procedure that accepts any number of inputs, as SUM does:

to max [:inputs] 2
if emptyp :inputs ~
   [(throw "error [not enough inputs to max])]
output reduce [ifelse ?1 > ?2 [?1] [?2]] :inputs
end

Nial

The behavior of multi-dimensional arrays is like J

max 1 2 3 4
=4

OCaml

<ocaml>exception Empty_list let rec my_max = function

  []      -> raise Empty_list
| [x]     -> x
| x :: xs -> max x (my_max xs)</ocaml>

Perl

<perl>sub max {

    my @list = @_;
    my $themax = $list[0];
    foreach ( @list ) {
         $themax = $_ > $themax ? $_ : $themax;
    }
    return $themax;

}</perl>

It is already implemented in the module List::Util's max() function: <perl>use List::Util qw(max);

max(@values);</perl>

PHP

The built-in PHP function max() already does this. <php>max($values)</php>

Python

The built-in Python function max() already does this. <python>max(values)</python>

Of course this assumes we have a list or tuple (or other sequence like object). (One can even find the max() or min() character of a string since that's treated as a sequence of characters and there are "less than" and "greater than" operations (object methods) associate with those characters).

If we truly were receiving a stream of data ... searching for the minimum would look something like:

<python> largest = 0 # or the minimal or epsilon value of the appropriate type while True:

   item = stream.readline()  # assuming line delimited inputs; use read(n) for fixed length inputs, etc.
   if not len(item):
       break  # assuming stream is any file-like object, providing a read() of len() == 0 at EOF
   try:
       item = int(item)  # using other functions to parse string inputs into any other data types
                         # import pack.unpack() from standard libraries to handle binary packed data
   except ValueError, e: # or, in Python3: except ValueError as e: ...
       pass
       # log or otherwise deal with errors here
   if item > largest:
       largest = item

</python>

As explained in the comments this example can be adapted for any sort of data being read over any sort of socket or file-like interface. The initial value of "largest" must be both comparable to the data that will be parsed from the stream ... and guarantee to be lower than the max item therefrom. Similarly a min() function would need some value that's guaranteed to be larger (sys.maxint, for example). (If the values might be large integers or some other intractable type then read one item from the stream before the loop to initialize the initial value ... then let the loop iterate over the rest).

Ruby

max is a method of all Enumerables values.max

Scheme

The built-in Scheme function max takes the max of all its arguments. <scheme>(max 1 2 3 4) (apply max values) ; find max of a list</scheme>

V

Assuming it is a list of positive numbers

[4 3 2 7 8 9] 0 [max] fold
=9

If it is not

[4 3 2 7 8 9] dup first [max] fold
=9