Greatest element of a list: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 3: Line 3:
=={{header|Ada}}==
=={{header|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.
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>
<lang ada>
with Ada.Text_Io;
with Ada.Text_Io;


Line 31: Line 31:
begin
begin
Ada.Text_IO.Put_Line(Float'Image(Max(Buf)));
Ada.Text_IO.Put_Line(Float'Image(Max(Buf)));
end Max_Test;</ada>
end Max_Test;</lang>
A generic function Max to deal with any floating-point type.
A generic function Max to deal with any floating-point type.
<Ada>
<Ada>
Line 109: Line 109:
{{works with|GCC}}
{{works with|GCC}}


<c>#include <stdarg.h>
<lang c>#include <stdarg.h>


#define MAX(A,...) ({ inline __typeof__ (A) _max_(__typeof__ (A) a, ...) {\
#define MAX(A,...) ({ inline __typeof__ (A) _max_(__typeof__ (A) a, ...) {\
Line 122: Line 122:
}\
}\
_max_((A),__VA_ARGS__);\
_max_((A),__VA_ARGS__);\
})</c>
})</lang>


=={{header|C++}}==
=={{header|C++}}==
This will work for any type with a < operator defined. Uses the standard library function <code>max_element()</code>.
This will work for any type with a < operator defined. Uses the standard library function <tt>max_element()</tt>.
<cpp>#include <algorithm>
<lang cpp>#include <algorithm>
#include <cassert>
#include <cassert>


Line 132: Line 132:
assert(count > 0);
assert(count > 0);
return *std::max_element(values, values + count);
return *std::max_element(values, values + count);
}</cpp>
}</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
The built-in Common Lisp function <code>max</code> takes the max of all its arguments.
The built-in Common Lisp function <tt>max</tt> takes the max of all its arguments.
<lisp>(max 1 2 3 4)
<lang lisp>(max 1 2 3 4)
(reduce #'max values) ; find max of a list
(reduce #'max values) ; find max of a list
(loop for x in values
(loop for x in values
maximize x) ; alternative way to find max of a list</lisp>
maximize x) ; alternative way to find max of a list</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 166: Line 166:


=={{header|Haskell}}==
=={{header|Haskell}}==
The built-in Haskell function <code>maximum</code> already does this.
The built-in Haskell function <tt>maximum</tt> already does this.
my_max = maximum
my_max = maximum
It can alternately be defined as a "fold" on the built-in two-argument <code>max</code> function.
It can alternately be defined as a "fold" on the built-in two-argument <tt>max</tt> function.
my_max = foldl1 max
my_max = foldl1 max


Line 193: Line 193:
=={{header|Java}}==
=={{header|Java}}==
The first function works with arrays of floats. Replace with arrays of double, int, or other primitive data type.
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 {
<lang java>public static float max(float[] values) throws NoSuchElementException {
if (values.length == 0)
if (values.length == 0)
throw new NoSuchElementException();
throw new NoSuchElementException();
Line 202: Line 202:
}
}
return themax;
return themax;
}</java>
}</lang>


Optionally, if it is OK to rearrange the contents of the original array:
Optionally, if it is OK to rearrange the contents of the original array:
<java>public static float max(float[] values) throws NoSuchElementException {
<lang java>public static float max(float[] values) throws NoSuchElementException {
if (values.length == 0)
if (values.length == 0)
throw new NoSuchElementException();
throw new NoSuchElementException();
Arrays.sort(values);//sorts the values in ascending order
Arrays.sort(values);//sorts the values in ascending order
return values[values.length-1];
return values[values.length-1];
}</java>
}</lang>


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 <code>Collections.max()</code> that already does this.
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 <tt>Collections.max()</tt> that already does this.
<java>public static <T extends Comparable<? super T>> T max(T[] values) throws NoSuchElementException {
<lang java>public static <T extends Comparable<? super T>> T max(T[] values) throws NoSuchElementException {
if (values.length == 0)
if (values.length == 0)
throw new NoSuchElementException();
throw new NoSuchElementException();
Line 229: Line 229:
public static <T extends Comparable<? super T>> T max(List<T> values) {
public static <T extends Comparable<? super T>> T max(List<T> values) {
return Collections.max(values);
return Collections.max(values);
}</java>
}</lang>


=={{header|Logo}}==
=={{header|Logo}}==
Line 258: Line 258:


=={{header|OCaml}}==
=={{header|OCaml}}==
<ocaml>let my_max = function
<lang ocaml>let my_max = function
[] -> invalid_arg "empty list"
[] -> invalid_arg "empty list"
| x::xs -> List.fold_left max x xs</ocaml>
| x::xs -> List.fold_left max x xs</lang>


# my_max [4;3;5;9;2;3] ;;
# my_max [4;3;5;9;2;3] ;;
Line 266: Line 266:


=={{header|Perl}}==
=={{header|Perl}}==
<perl>sub max {
<lang perl>sub max {
my @list = @_;
my @list = @_;
my $themax = $list[0];
my $themax = $list[0];
Line 273: Line 273:
}
}
return $themax;
return $themax;
}</perl>
}</lang>


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


max(@values);</perl>
max(@values);</lang>


=={{header|PHP}}==
=={{header|PHP}}==
The built-in PHP function <code>max()</code> already does this.
The built-in PHP function <tt>max()</tt> already does this.
<php>max($values)</php>
<lang php>max($values)</lang>


=={{header|Python}}==
=={{header|Python}}==
The built-in Python function <code>max()</code> already does this.
The built-in Python function <tt>max()</tt> already does this.
<python>max(values)</python>
<lang python>max(values)</lang>


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).
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).
Line 293: Line 293:


max(), (and min()), can take iterables and a key argument which takes a function that can transform each item into a type that we can compare, for example, if the stream were returning string representations of integers, one to a line, you could do
max(), (and min()), can take iterables and a key argument which takes a function that can transform each item into a type that we can compare, for example, if the stream were returning string representations of integers, one to a line, you could do
<python>>>> floatstrings = ['1\n', ' 2.3\n', '4.5e-1\n', '0.01e4\n', '-1.2']
<lang python>>>> floatstrings = ['1\n', ' 2.3\n', '4.5e-1\n', '0.01e4\n', '-1.2']
>>> max(floatstrings, key = float)
>>> max(floatstrings, key = float)
'0.01e4\n'
'0.01e4\n'
>>> </python>
>>> </lang>
Normally we would want the converted form as the maximum and we could just as easily write:
Normally we would want the converted form as the maximum and we could just as easily write:
<python>>>> max(float(x) for x in floatstrings)
<lang python>>>> max(float(x) for x in floatstrings)
100.0
100.0
>>> </python>
>>> </lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<code>max</code> is a method of all Enumerables
<tt>max</tt> is a method of all Enumerables
<ruby>values.max</ruby>
<lang ruby>values.max</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
The built-in Scheme function <code>max</code> takes the max of all its arguments.
The built-in Scheme function <tt>max</tt> takes the max of all its arguments.
<scheme>(max 1 2 3 4)
<lang scheme>(max 1 2 3 4)
(apply max values) ; find max of a list</scheme>
(apply max values) ; find max of a list</lang>


=={{header|V}}==
=={{header|V}}==

Revision as of 15:41, 3 February 2009

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. <lang 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;</lang> 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.

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - using print instead of printf
# substitute any array type with a scalar element #
MODE FLT = REAL;

# create an exception for the case of an empty array #
PROC raise empty array = VOID:(
  GO TO except empty array
);

PROC max = ([]FLT item)FLT:
BEGIN
   IF LWB item > UPB item THEN
      raise empty array; SKIP
   ELSE
     FLT max element := item[LWB item];

     FOR i FROM LWB item + 1 TO UPB item DO
       IF item[i] > max element THEN
         max element := item[i]
       FI
     OD;
     max element
   FI
END # max #;

[]FLT buf = (-275.0, -111.19, 0.0, -1234568.0, pi, -pi);
print((max(buf),new line)) EXIT
except empty array:
  SKIP

Output:

+3.14159265358979e  +0

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>

The following macro can be used with any number and type of arguments, provided that the arguments are simple, i.e. must not contain subexpressions where commas appear (this is because of the way the arguments are counted; the macro can be modified so that it is up to the caller to count the number of arguments passed).

Works with: GCC

<lang c>#include <stdarg.h>

  1. define MAX(A,...) ({ inline __typeof__ (A) _max_(__typeof__ (A) a, ...) {\
 va_list l; int i,c; char *s = #__VA_ARGS__; __typeof__ (A) max = a;\
 __typeof__ (A) t;\
 for(c=1;*s!=0;s++) if (*s==',') c++;\
 va_start(l, a);\
 for(i=0;i<=c;i++) {\
 if ((t=va_arg(l,__typeof__ (A))) > max) max = t;\
 }\
 va_end(l); return max;\

}\ _max_((A),__VA_ARGS__);\ })</lang>

C++

This will work for any type with a < operator defined. Uses the standard library function max_element(). <lang 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);

}</lang>

Common Lisp

The built-in Common Lisp function max takes the max of all its arguments. <lang 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</lang>

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

Icon

procedure main()
   local l
   l := [7,8,6,9,4,5,2,3,1]
   write(max(l))
end

procedure max(l)
   local i, max
   max := l[1]
   every i := 1 to !l & i > max do
       max := i
   return max
end

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. <lang 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;

}</lang>

Optionally, if it is OK to rearrange the contents of the original array: <lang 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];

}</lang>

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. <lang 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);

}</lang>

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

<lang ocaml>let my_max = function

   [] -> invalid_arg "empty list"
 | x::xs -> List.fold_left max x xs</lang>
# my_max [4;3;5;9;2;3] ;;
- : int = 9

Perl

<lang perl>sub max {

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

}</lang>

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

max(@values);</lang>

PHP

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

Python

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

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 then in Python, such streams are usually iterable, meaning they have a way of generating one item at a time from the stream.

max(), (and min()), can take iterables and a key argument which takes a function that can transform each item into a type that we can compare, for example, if the stream were returning string representations of integers, one to a line, you could do <lang python>>>> floatstrings = ['1\n', ' 2.3\n', '4.5e-1\n', '0.01e4\n', '-1.2'] >>> max(floatstrings, key = float) '0.01e4\n' >>> </lang> Normally we would want the converted form as the maximum and we could just as easily write: <lang python>>>> max(float(x) for x in floatstrings) 100.0 >>> </lang>

Ruby

max is a method of all Enumerables <lang ruby>values.max</lang>

Scheme

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

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