Greatest element of a list

From Rosetta Code
Jump to: navigation, search
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 may not be known until runtime.

Contents

[edit] ACL2

(defun maximum (xs)
(if (endp (rest xs))
(first xs)
(max (first xs)
(maximum (rest xs)))))

[edit] ActionScript

function max(... args):Number
{
var curMax:Number = -Infinity;
for(var i:uint = 0; i < args.length; i++)
curMax = Math.max(curMax, args[i]);
return curMax;
}

[edit] 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.

with Ada.Text_Io;
 
procedure Max_Test isco
-- 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;

A generic function Max to deal with any floating-point type.

generic
type Item is digits <>;
type Items_Array is array (Positive range <>) of Item;
function Generic_Max (List : Items_Array) return Item;

Implementation of:

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;

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.

[edit] Aime

integer
lmax(list l)
{
integer i, max, x;
 
max = l[0];
 
i = 1;
while (i < l_length(l)) {
x = l[i];
if (max < x) {
max = x;
}
 
i += 1;
}
 
return max;
}

[edit] ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
# 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 #;
 
test:(
[]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

[edit] APL

LIST←2 4 6 3 8
⌈/LIST
Output:
8

[edit] AppleScript

on max(aList)
set _curMax to first item of aList
repeat with i in (rest of aList)
if i > _curMax then set _curMax to contents of i
end repeat
return _curMax
end max

[edit] Applesoft BASIC

 100 REMMAX
110 R$ = "":E$ = ""
120 L = LEN (L$)
130 IF L = 0 THEN RETURN
140 FOR I = 1 TO L
150 C$ = MID$ (L$,I,1)
160 SP = C$ = " "
170 IF SP THEN GOSUB 200
180 E$ = E$ + C$
190 NEXT I
200 C$ = ""
210 IF E$ = "" THEN RETURN
220 V = VAL (E$):V$ = R$
230 E$ = "":E = V$ = ""
240 IF E AND V = 0 THEN RETURN
250 R$ = STR$ (V)
260 IF E THEN RETURN
270 R = VAL (V$)
280 IF R < V THEN RETURN
290 R$ = V$: RETURN
L$ = "1 2 3 4 20 6 11 3 9 7"
GOSUB 100MAX
PRINT R$
Output:
20

[edit] AutoHotkey

[edit] CSV Data

list = 1,5,17,-2
Loop Parse, list, `,
x := x < A_LoopField ? A_LoopField : x
MsgBox Max = %x%

[edit] Pseudo-arrays

list = 1,5,17,-2
StringSplit, list, list,`, ; creates a pseudo-array
Loop % List0
x := x < List%A_Index% ? List%A_Index% : x
MsgBox Max = %x%

[edit] True arrays

Works with: AutoHotkey_L
List := [1,5,17,-2]
For each, value in List
x := x < value ? value : x
MsgBox Max = %x%

[edit] AWK

One-liner:

$ awk 'func max(a){for(i in a)if(a[i]>r)r=a[i];return r}BEGIN{a[0]=42;a[1]=33;a[2]=21;print max(a)}'
42

More readable version:

 
# Usage: awk -f greatest_list_element.awk
#
function max(a) {
for(i in a) if(a[i]>r) r=a[i];
return r
}
#
BEGIN { a[0]=42;
a[1]=33;
a[2]=21;
print max(a)
}
 

[edit] BASIC

Works with: QBasic
DECLARE SUB addVal (value AS INTEGER)
DECLARE FUNCTION findMax% ()
 
REDIM SHARED vals(0) AS INTEGER
DIM SHARED valCount AS INTEGER
DIM x AS INTEGER, y AS INTEGER
 
valCount = -1
 
'''''begin test run
RANDOMIZE TIMER
FOR x = 1 TO 10
y = INT(RND * 100)
addVal y
PRINT y; " ";
NEXT
PRINT ": "; findMax
'''''end test run
 
SUB addVal (value AS INTEGER)
DIM tmp AS INTEGER
IF valCount > -1 THEN
'this is needed for BASICs that don't support REDIM PRESERVE
REDIM v2(valCount) AS INTEGER
FOR tmp = 0 TO valCount
v2(tmp) = vals(tmp)
NEXT
END IF
valCount = valCount + 1
REDIM vals(valCount)
IF valCount > 0 THEN
'also needed for BASICs that don't support REDIM PRESERVE
FOR tmp = 0 TO valCount - 1
vals(tmp) = v2(tmp)
NEXT
END IF
vals(valCount) = value
END SUB
 
FUNCTION findMax%
DIM tmp1 AS INTEGER, tmp2 AS INTEGER
FOR tmp1 = 0 TO valCount
IF vals(tmp1) > tmp2 THEN tmp2 = vals(tmp1)
NEXT
findMax = tmp2
END FUNCTION
Output:
 8162   5139   7004   7393   5151   4476   577   4419   3333   4649  :  8162

See also: BBC BASIC, Liberty BASIC, PowerBASIC, PureBasic, Run BASIC, TI-89 BASIC, Visual Basic

[edit] Batch File

::max.cmd
@echo off
setlocal enabledelayedexpansion
set a=.%~1
if "%a%" equ "." set /p a="Input stream: "
call :max res %a%
echo %res%
endlocal
goto :eof
 
:max
set %1=%2
:loop
shift /2
if "%2" equ "" goto :eof
if %2 gtr !%1! set res=%2
goto loop

Invocation from command line or from internal prompt

>max "123 456 3 234243 12"
234243
 
>max
Input stream: 5 4 3 2 67 1
67

[edit] BBC BASIC

      ListOfValues$ = "13, 0, -6, 2, 37, -10, 12"
PRINT "Maximum value = " ; FNmax(ListOfValues$)
END
 
DEF FNmax(list$)
LOCAL index%, number, max
REPEAT
number = VAL(MID$(list$, index%+1))
IF number > max THEN max = number
index% = INSTR(list$, ",", index%+1)
UNTIL index% = 0
= max

[edit] bc

define m(a[], n) {
auto m, i
 
m = a[0]
for (i = 1; i < n; i++) {
if (a[i] > m) m = a[i]
}
return(m)
}

[edit] Bracmat

When comparing two rational numbers, Bracmat compares numerically. In all other cases Bracmat compares lexically.

  ( biggest
= max
.  !arg:
|  !arg:%?max ?arg
& !arg:? (%@:>!max:?max) (?&~)
| !max
)
& out$("1:" biggest$(5 100000 -5 aap 3446 NOOT mies 0))
& out$("2:" biggest$)
& out
$ ( "3:"
biggest
$ (5 100000 -5 43756243978569758/13 3365864921428443 87512487957139516/27 3446)
)
Output:
1: mies
2:
3: 3365864921428443

[edit] Brat

Arrays have a max function, but here's a manual implementation.

max = { list |
list.reduce { n, max |
true? n > max
{ max = n }
{ max }
}
}
 
p max [3 4 1 2]

[edit] Burlesque

 
blsq ) {88 99 77 66 55}>]
99
 

[edit] C

This works well with floats. Replace with double, int or what-have-you before passing a different data type.

#include <assert.h>
 
float max(unsigned int count, float values[]) {
assert(count > 0);
unsigned int idx;
float themax = values[0];
for(i = 1; i < count; ++i) {
themax = values[i] > themax ? values[i] : themax;
}
return themax;
}

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
#include <stdarg.h>
 
#define MAX(A,...) ({ inline __typeof__ (A) _max_(__typeof__ (A) a, ...) {\
va_list l; int i,c; const 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__);\
})

[edit] C++

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

#include <algorithm>
#include <cassert>
 
template<typename Ty> Ty max(unsigned int count, Ty values[]) {
assert(count > 0);
return *std::max_element(values, values + count);
}

[edit] C#

C# already has a "Maximum Value" function.

using System.Linq;
 
values.Max();

[edit] Clojure

The Clojure.core function max returns the max of its arguments.

(max 1 2 3 4) ; evaluates to 4
;; If the values are already in a collection, use apply:
(apply max [1 2 3 4]) ; evaluates to 4

[edit] CMake

Only for lists of integers.

# max(var [value1 value2...]) sets var to the maximum of a list of
# integers. If list is empty, sets var to NO.
function(max var)
set(first YES)
set(choice NO)
foreach(item ${ARGN})
if(first)
set(choice ${item})
set(first NO)
elseif(choice LESS ${item})
set(choice ${item})
endif()
endforeach(item)
set(${var} ${choice} PARENT_SCOPE)
endfunction(max)
 
set(list 33 11 44 22 66 55)
max(maximum ${list})
message(STATUS "maximum of ${list} => ${maximum}")
-- maximum of 33;11;44;22;66;55 => 66

[edit] COBOL

This is already built into the language for tables of numbers.

DISPLAY FUNCTION MAX(nums (ALL))

A sample implementation:

       IDENTIFICATION DIVISION.
FUNCTION-ID. greatest-elt.
 
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 idx USAGE INDEX.
 
01 Table-Len CONSTANT 50.
 
LINKAGE SECTION.
01 num-table-area.
03 num-table PIC 9(8) OCCURS Table-Len TIMES.
 
01 max-elt PIC 9(8).
 
PROCEDURE DIVISION USING VALUE num-table-area RETURNING max-elt.
PERFORM VARYING idx FROM 1 BY 1 UNTIL idx > Table-Len
IF num-table (idx) > max-elt
MOVE num-table (idx) TO max-elt
END-IF
END-PERFORM
 
GOBACK
.
END FUNCTION greatest-elt.

[edit] CoffeeScript

 
# using Math library
max1 = (list) ->
Math.max.apply null, list
 
# using no libraries
max2 = (list) ->
maxVal = list[0]
for value in list
maxVal = value if value > maxVal
maxVal
 
 
 
# Test it
a = [0,1,2,5,4];
alert(max1(a)+". The answer is "+max2(a));
 

[edit] ColdFusion

 
<Cfset theList = '1, 1000, 250, 13'>
<Cfparam name="maxNum" default=0>
<Cfloop list="#theList#" index="i">
<Cfif i gt maxNum><Cfset maxNum = i></Cfif>
</Cfloop>
<Cfoutput>#maxNum#</Cfoutput>
 
 
<Cfset theList = '1, 1000, 250, 13'>
<Cfset maxNum = ListFirst(ListSort(thelist, "numeric", "desc"))>
<Cfoutput>#maxNum#</Cfoutput>
 

[edit] Common Lisp

The built-in Common Lisp function max takes the max of all its arguments.

(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

[edit] Component Pascal

BalckBox Component Builder

 
MODULE Operations;
IMPORT StdLog,Args,Strings;
 
PROCEDURE Max(s: ARRAY OF INTEGER): INTEGER;
VAR
i: INTEGER;
max: INTEGER;
BEGIN
max := MIN(INTEGER);
FOR i := 0 TO LEN(s) - 1 DO
max := MAX(max,s[i]);
END;
RETURN max
END Max;
 
PROCEDURE DoMax*;
VAR
sq: POINTER TO ARRAY OF INTEGER;
p: Args.Params;
i,n,done: INTEGER;
BEGIN
Args.Get(p);
IF p.argc > 0 THEN
NEW(sq,p.argc);
FOR i := 0 TO p.argc - 1 DO
Strings.StringToInt(p.args[i],n,done);
sq[i] := n
END;
StdLog.String("max:> ");StdLog.Int(Max(sq));StdLog.Ln
END
END DoMax;
 
END Operations.
 

Execute: ^Q Operations..DoMax 23 12 3 45 34 54 84 ~

Output:
max:>  84

[edit] D

void main() {
import std.stdio, std.algorithm;
 
[9, 4, 3, 8, 5].reduce!max.writeln;
}
Output:
9

[edit] Dart

/*This is a function which returns the greatest element in a list of numbers */
num findGreatestElement(List<num> list){
num greatestElement = list[0];
for (num element in list){
if (element>greatestElement) {
greatestElement = element;
}
}
return greatestElement;
}
 

[edit] Delphi

Math.MaxIntValue(); // Array of Integer
Math.MaxValue(); // Array of floating point (Single, Double or Extended)
 

[edit] Déjà Vu

max lst:
lst! 0
for item in copy lst:
if > item dup:
item drop
 
!. max [ 10 300 999 9 ]
Output:
999

[edit] E

This function works for any value which responds to max/1:

pragma.enable("accumulator") # non-finalized syntax feature
 
def max([first] + rest) {
return accum first for x in rest { _.max(x) }
}
? max([1, 2, 3])
# value: 3

To require only the comparison protocol, one needs to write out the algorithm a little more explicitly:

def max([var bestSoFar] + rest) {
for x ? (x > bestSoFar) in rest {
bestSoFar := x
}
return bestSoFar
}
? max([1, 3, 2])
# value: 3
 
? max([[1].asSet(), [2].asSet(), [1, 2].asSet()])
# value: [1, 2].asSet()

[edit] ECL

 
 
MaxVal(SET OF INTEGER s) := MAX(s);
 
//example usage
 
SetVals := [4,8,16,2,1];
MaxVal(SetVals) //returns 16;
 
 

[edit] Efene

list_max = fn ([Head:Rest]) {
list_max(Rest, Head)
}
 
list_max = fn ([], Res) {
Res
}
fn ([Head:Rest], Max) when Head > Max {
list_max(Rest, Head)
}
fn ([_Head:Rest], Max) {
list_max(Rest, Max)
}
 
list_max1 = fn ([H:T]) {
lists.foldl(fn erlang.max:2, H, T)
}
 
@public
run = fn () {
io.format("~p~n", [list_max([9, 4, 3, 8, 5])])
io.format("~p~n", [list_max1([9, 4, 3, 8, 5])])
}
 

[edit] Eiffel

The GREATEST_ELEMENT class:

 
class
GREATEST_ELEMENT [G -> COMPARABLE]
 
create
make
 
feature {NONE} --Implementation
 
is_max (element: G maximum: G): BOOLEAN
do
Result := maximum >= element
end
 
max (list: ARRAY [G]): G
require
not_empty: not list.is_empty
do
Result := list [list.lower]
across
list as i
loop
Result := i.item.max (Result)
end
ensure
is_part_of_array: list.has (Result)
is_maximum: list.for_all (agent is_max(?, Result))
end
 
feature -- Initialization
 
make
do
end
 
greatest_element (a: ARRAY [G]): G
do
Result := max (a)
end
 
end
 

A test application:

 
class
APPLICATION
 
create
make
 
feature {NONE} -- Initialization
 
make
-- Run application.
local
numbers: ARRAY [INTEGER]
greatest: GREATEST_ELEMENT [INTEGER]
do
create greatest.make
numbers := <<1, 2, 3, 4, 5, 6, 7, 8, 9>>
print (greatest.greatest_element (numbers))
end
 
end
 

[edit] Ela

open list
 
findBy p (x::xs) = foldl (\x y | p x y -> x | else -> y) x xs
maximum = findBy (>)
 
maximum [1..10]

[edit] Emacs Lisp

(defun max (first-arg &rest more-args)
(if more-args
(let ((max-rest (apply 'max more-args)))
(if (> first-arg max-rest)
first-arg
max-rest))
first-arg))

Example use:

(max 2 7 5)
7

[edit] Erlang

Builtin. Using it from the Erlang shell:

>lists:max([9,4,3,8,5]).
9

[edit] Euler Math Toolbox

 
>v=random(1,100);
>max(v)
0.997492478596
 

[edit] Euphoria

[edit] Applying a function to each element of an array

function aeval( sequence sArr, integer id )
for i = 1 to length( sArr ) do
sArr[ i ] = call_func( id, { sArr[ i ] } )
end for
return sArr
end function
 
object biggun
function biggest( object elem )
if compare(elem, biggun) > 0 then
biggun = elem
end if
return elem
end function
 
biggun = 0
object a
a = aeval( {1,1234,62,234,12,34,6}, routine_id("biggest") )
printf( 1, "%d\n", biggun )
 
sequence s
s = {"antelope", "dog", "cat", "cow", "wolf", "wolverine", "aardvark"}
biggun = "ant"
a = aeval( s, routine_id("biggest") )
printf( 1, "%s\n", {biggun} )
Output:
1234
wolverine

[edit] More trivial example

function get_biggest(sequence s)
object biggun
biggun = s[1]
for i = 2 to length(s) do
if compare(s[i], biggun) > 0 then
biggun = s[i]
end if
end for
return biggun
end function
 
constant numbers = {1,1234,62,234,12,34,6}
printf(1,"%d\n",get_biggest(numbers))
 
constant animals = {"ant", "antelope", "dog", "cat", "cow", "wolf", "wolverine", "aardvark"}
printf(1,"%s\n",{get_biggest(animals)})
Output:
1234
wolverine

[edit] F#

F# has a built in function for getting the max of a list:

>[2;3;4;5;36;3;2;6;7] |> List.max;;
val it : int = 36

To use as a function

let ListMax n = n |> List.max

[edit] Factor

The following word is in factor's standard library.

: supremum ( seq -- elt ) [ ] [ max ] map-reduce ;

[edit] Fancy

[1,-2,2,4,6,-4,-1,5] max println  # => 6

[edit] Fantom

Has a built-in method to get maximum from a list.

 
class Greatest
{
public static Void main ()
{
Int[] values := [1,2,3,4,5,6,7,8,9]
Int greatest := values.max
echo (greatest)
}
}
 

[edit] 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 ;

[edit] Fortran

Works with: Fortran version 2003

The intrinsic function maxval returns the maximum value of the elements in an integer or real array:

program test_maxval
 
integer,dimension(5),parameter :: x = [10,100,7,1,2]
real,dimension(5),parameter :: y = [5.0,60.0,1.0,678.0,0.0]
 
write(*,'(I5)') maxval(x)
write(*,'(F5.1)') maxval(y)
 
end program test_maxval
Output:
 100
 678.0

The intrinsic function max accepts any number of arguments. The type of these arguments can be integer, real, character, string of characters or arrays of these.

program test_max
 
implicit none
 
write (*, '(i0)') &
& max (1, 2, 3)
write (*, '(f3.1)') &
& max (1.0, 2.0, 3.0)
write (*, '(a)') &
& max ('a', 'b', 'c')
write (*, '(a)') &
& max ('abc', 'bca', 'cab')
write (*, '(i0, 2 (1x, i0))') &
& max ([1, 8, 6], [7, 5, 3], [4, 2, 9])
write (*, '(f3.1, 2 (1x, f3.1))') &
& max ([1.0, 8.0, 6.0], [7.0, 5.0, 3.0], [4.0, 2.0, 9.0])
write (*, '(a, 2 (1x, a))') &
& max (['a', 'h', 'f'], ['g', 'e', 'c'], ['d', 'b', 'i'])
write (*, '(a, 2 (1x, a))') &
& max (['abc', 'hig', 'fde'], ['ghi', 'efd', 'cab'], ['def', 'bca', 'igh'])
 
end program test_max
Output:
 3
 3.0
 c
 cab
 7 8 9
 7.0 8.0 9.0
 g h i
 ghi hig igh

[edit] Frink

 
println[max[[1,2,3,5,10,20]]]
 

[edit] FunL

Using the pre-defined function max:

println( max([1,2,3,-1,0]) )
Output:
3

It can be implemented as:

def
maximum( xs ) =
def
max( a, b ) = if a <= b then b else a
 
foldl( f, z, [] ) = z
foldl( f, z, x:xs ) = foldl( f, f(z, x), xs )
 
foldl1( f, x:xs ) = foldl( f, x, xs )
foldl1( _, [] ) = error( "foldl1: empty list" )
 
foldl1( max, xs )

[edit] GAP

# Built-in
 
L := List([1 .. 100], n -> Random(1, 10));
 
MaximumList(L);
# 10

[edit] Go

List

The task title says list. This solution uses a Go slice as a list.

package main
 
import (
"fmt"
"math/rand"
"time"
)
 
// function, per task description
func largest(a []int) (lg int, ok bool) {
if len(a) == 0 {
return
}
lg = a[0]
for _, e := range a[1:] {
if e > lg {
lg = e
}
}
return lg, true
}
 
func main() {
// random size slice
rand.Seed(time.Now().UnixNano())
a := make([]int, rand.Intn(11))
for i := range a {
a[i] = rand.Intn(101) - 100 // fill with random numbers
}
 
fmt.Println(a)
lg, ok := largest(a)
if ok {
fmt.Println(lg)
} else {
fmt.Println("empty list. no maximum.")
}
}
Set

The task description says set. This solution uses a Go map as a set.

package main
 
import (
"fmt"
"math"
"math/rand"
"time"
)
 
// Function, per task description. Interesting with the float64 type because
// of the NaN value. NaNs do not compare to other values, so the result of
// a "largest" function on a set containing a NaN might be open to
// interpretation. The solution provided here is to return the largest
// of the non-NaNs, and also return a bool indicating the presense of a NaN.
func largest(s map[float64]bool) (lg float64, ok, nan bool) {
if len(s) == 0 {
return
}
for e := range s {
switch {
case math.IsNaN(e):
nan = true
case !ok || e > lg:
lg = e
ok = true
}
}
return
}
 
func main() {
rand.Seed(time.Now().UnixNano())
// taking "set" literally from task description
s := map[float64]bool{}
// pick number of elements to add to set
n := rand.Intn(11)
// add random numbers, also throw in an occasional NaN or Inf.
for i := 0; i < n; i++ {
switch rand.Intn(10) {
case 0:
s[math.NaN()] = true
case 1:
s[math.Inf(1)] = true
default:
s[rand.ExpFloat64()] = true
}
}
 
fmt.Print("s:")
for e := range s {
fmt.Print(" ", e)
}
fmt.Println()
switch lg, ok, nan := largest(s); {
case ok && !nan:
fmt.Println("largest:", lg)
case ok:
fmt.Println("largest:", lg, "(NaN present in data)")
case nan:
fmt.Println("no largest, all data NaN")
default:
fmt.Println("no largest, empty set")
}
}

[edit] Golfscript

{$-1=}:max;
[1 4 8 42 6 3]max # Example usage

[edit] Groovy

println ([2,4,0,3,1,2,-12].max())
Output:
4

[edit] 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

[edit] HicEst

 
max_value = MAX( -123, 234.56, 345.678, -456E3, -455) ! built-in function MAX(...)
 
! or for an array:
max_value = MAX( array_of_values )
 
! or to find a maximum value in a file named filename:
CHARACTER List, filename='Greatest element of a list.hic' ! filename contains this script
REAL values(1) ! unknown number of values, allocate more below
 
OPEN(FIle=filename, BINary, LENgth=len)
ALLOCATE(values, len/2) ! number of values <= half byte count of file
! read all values, returns item count in values_found:
READ(FIle=filename, ItemS=values_found, CLoSe=1) values ! no Format needed for plain text numbers
 
max_value = MAX(values)
 
! write values found in filename and result to spreadsheet type dialog window:
DLG(Text=values, Text=max_value, TItle=values_found)
 
WRITE(ClipBoard, Name) max_value, values_found, values ! pasted to line below
! max_value=345.678; values_found=30; values(1)=-123; values(2)=234.56; values(3)=345.678; values(4)=-456E3; values(5)=-455; values(6)=1; values(7)=2; values(8)=1; values(9)=0; values(10)=0; ...truncated
END
 

[edit] Icon and Unicon

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

[edit] J

Solution:
   >./
Example:
   >./ 1 2 3 2 1
3
>./'' NB. Maximum value of an empty list = identity element (or neutral) of max = -∞
__

[edit] Java

The first function works with arrays of floats. Replace with arrays of double, int, or other primitive data type.

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;
}

Optionally, if it is OK to rearrange the contents of the original array:

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];
}

The following functions work with Lists or arrays 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. For arrays, we can just use the Arrays.asList() wrapper to wrap it into a list and then use the function for lists.

import java.util.List;
import java.util.Collections;
import java.util.Arrays;
 
public static <T extends Comparable<? super T>> T max(List<T> values) {
return Collections.max(values);
}
 
public static <T extends Comparable<? super T>> T max(T[] values) {
return Collections.max(Arrays.asList(values));
}

[edit] JavaScript

[edit] ES3-5

Math.max.apply(null, [ 0, 1, 2, 5, 4 ]); // 5

[edit] ES6

Math.max(...[ 0, 1, 2, 5, 4 ]); // 5

[edit] jq

jq's sort defines an ordering of all JSON entities, and the max filter accordingly can be used on any JSON array:

[1, 3, 1.0] | max # => 3
 
[ {"a": 1}, {"a":3}, {"a":1.0}] | max # => {"a": 3}
 

[edit] Julia

Using the built-in maximum function:

julia> maximum([1,3,3,7])
7
 
julia> maximum([pi,e+2/5,cos(6)/5,sqrt(91/10)])
3.141592653589793
 
julia> maximum([1,6,Inf])
Inf
 
julia> maximum(Float64[])
maximum: argument is empty
at In[138]:1
in maximum at abstractarray.jl:1591
 

(Note that it throws an exception on an empty array.)

[edit] K

  |/ 6 1 7 4
7


[edit] Lasso

define greatest(a::array) => {
return (#a->sort&)->last
}
 
local(x = array(556,1,7344,4,7,52,22,55,88,122,55,99,1222,578))
greatest(#x)
Output:
7344

[edit] LFE

Builtin. Using it from the LFE shell:

>(: lists max '[9 4 3 8 5])
9


[edit] Liberty BASIC

aList$= "1 15 -5 6 39 1.5 14"
 
maxVal = val(word$(aList$, 1))
token$ = "?"
while token$ <> ""
index = index + 1
token$ = word$(aList$, index)
aVal = val(token$)
if aVal > maxVal then maxVal = aVal
wend
 
print "maxVal = ";maxVal

[edit]

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

[edit] Logtalk

 
max([X| Xs], Max) :-
max(Xs, X, Max).
 
max([], Max, Max).
max([X| Xs], Aux, Max) :-
( X @> Aux ->
max(Xs, X, Max)
; max(Xs, Aux, Max)
).

[edit] Lua

-- Table to store values
local values = {}
-- Read in the first number from stdin
local new_val = io.read"*n"
-- Append all numbers passed in
-- until there are no more numbers (io.read'*n' = nil)
while new_val do
values[#values+1] = new_val
new_val = io.read"*n"
end
 
-- Print the max
print(math.max(unpack(values)))
 

[edit] Maple

This is a built-in, polymorphic procedure in Maple.

> max( { 1, 2,  Pi, exp(1) } ); # set
Pi
 
> max( [ 1, 2, Pi, exp(1) ] ); # list
Pi
 
> max( 1, 2, Pi, exp(1) ); # sequence
Pi
 
> max( Array( [ 1, 2, Pi, exp(1) ] ) ); # Array
Pi

For numeric data in (multi-dimensional) rtables, a particularly flexible and powerful method for finding the maximum (and many other things) is the use of "rtable_scanblock". The maximum of an Array is a built-in rtable_scanblock operation and can be found as follows.

> A := Array([1,2,4/5,3,11]): rtable_scanblock( A, [rtable_dims(A)], Maximum ); 
11

[edit] Mathematica

Input:

Max[1, 3, 3, 7]
Max[Pi,E+2/5,17 Cos[6]/5,Sqrt[91/10]]
Max[1,6,Infinity]
Max[]
Output:
 7
 17 Cos[6]/5
 Infinity
-Infinity

Note that Max returns minus infinity if supplied with no arguments; as it should:

Max[Max[],Max[a,b,c]]
Max[Max[a],Max[b,c]]
Max[Max[a,b],Max[c]]
Max[Max[a,b,c],Max[]]

should all give the same results, therefore max[] should give -Infinity. If it WOULD give 0 strange this can happen:

Max[Max[], Max[-4, -3]]

WOULD give 0 instead of -3

[edit] MATLAB

function [maxValue] = findmax(setOfValues)
maxValue = max(setOfValues);

[edit] Maxima

: makelist(random(1000), 50)$
 
/* Three solutions */
lreduce(max, u);
 
apply(max, u);
 
lmax(u);

[edit] MAXScript

MAXScript has a built-in function called amax(), which will return the maximum of an array or the values supplied to it. The following custom function will return the maximum of the array supplied to it, or 'undefined' if an empty array is supplied.

fn MaxValue AnArray = 
(
if AnArray.count != 0 then
(
local maxVal = 0
for i in AnArray do if i > maxVal then maxVal = i
maxVal
)
else undefined
)

[edit] Metafont

The max macro (in the base set of macro for Metafont) accepts any number of arguments, and accepts both numerics (numbers), pairs (bidimensional vectors), and strings (not mixed).

show max(4,5,20,1);
show max((12,3), (10,10), (25,5));
show max("hello", "world", "Hello World");

[edit] МК-61/52

П0	С/П	x=0	07	ИП0	x<0	00	max	БП	00

or

П0	ИП0	С/П	-	x<0	01	Вx	П0	БП	01

[edit] Modula-3

Modula-3 provides a builtin MAX function, but it only works on two elements (or enumerations) but not arrays or sets.

We provide a generic Maximum implementation:

GENERIC INTERFACE Maximum(Elem);
 
EXCEPTION Empty;
 
PROCEDURE Max(READONLY a: ARRAY OF Elem.T): Elem.T RAISES {Empty};
 
END Maximum.
GENERIC MODULE Maximum(Elem);
 
PROCEDURE Max(READONLY arr: ARRAY OF Elem.T): Elem.T RAISES {Empty} =
VAR max := FIRST(Elem.T);
BEGIN
IF NUMBER(arr) = 0 THEN
RAISE Empty;
END;
FOR i := FIRST(arr) TO LAST(arr) DO
IF arr[i] > max THEN
max := arr[i];
END;
END;
RETURN max;
END Max;
 
BEGIN
END Maximum.

Elem can be instantiated to any type (any type that can be compared with the '>' function). For convenience Modula-3 provides interfaces/modules for the built in types, like Integer, Real, LongReal, etc, which contain type definitions as well as properties specific to the type.

To make a generic interface/module for a specific type, you must instantiate it:

INTERFACE RealMax = Maximum(Real) END RealMax.
MODULE RealMax = Maximum(Real) END RealMax.

Now we can import RealMax into our source and use the Max function:

MODULE Main;
 
IMPORT RealMax, IO, Fmt;
 
VAR realarr := ARRAY [1..5] OF REAL {1.1, 1.0, 0.0, 2.4, 3.3};
 
BEGIN
IO.Put(Fmt.Real(RealMax.Max(realarr)) & "\n");
END Main.

[edit] MUMPS

 
MV(A,U)
 ;A is a list of values separated by the string U
NEW MAX,T,I
FOR I=1:1 SET T=$PIECE(A,U,I) QUIT:T="" S MAX=$SELECT(($DATA(MAX)=0):T,(MAX<T):T,(MAX>=T):MAX)
QUIT MAX
 

Usage:

USER>SET V=","
 
USER>SET B="-1,-1000,1000,2.3E5,8A,""A"",F"
 
USER>W $$MV^ROSETTA(B,V)
2.3E5

[edit] Nemerle

using System;
using Nemerle.Collections;
using System.Linq;
using System.Console;
 
module SeqMax
{
SeqMax[T, U] (this seq : T) : U
where T : Seq[U]
where U : IComparable
{
$[s | s in seq].Fold(seq.First(), (x, y) => {if (x.CompareTo(y) > 0) x else y})
}
 
Main() : void
{
def numbers = [1, 12, 3, -5, 6, 23];
def letters = ['s', 'p', 'a', 'm'];
 
// using SeqMax() method (as task says to "create a function")
WriteLine($"numbers.SeqMax() = $(numbers.SeqMax())");
WriteLine($"letters.SeqMax() = $(letters.SeqMax())");
 
// using the already available Max() method
WriteLine($"numbers.Max() = $(numbers.Max())");
WriteLine($"letters.Max() = $(letters.Max())")
}
}
Output:
numbers.SeqMax() = 23
letters.SeqMax() = s
numbers.Max() = 23
letters.Max() = s

[edit] NetRexx

/* NetRexx */
 
options replace format comments java crossref savelog symbols binary
 
rn = Random()
maxElmts = 100
dlist = double[maxElmts]
rlist = Rexx[maxElmts]
loop r_ = 0 to maxElmts - 1
nr = rn.nextGaussian * 100.0
dlist[r_] = nr
rlist[r_] = Rexx(nr)
end r_
 
say 'Max double:' Rexx(getMax(dlist)).format(4, 9)
say 'Max Rexx:' getMax(rlist).format(4, 9)
 
return
 
method getMax(dlist = double[]) public static binary returns double
dmax = Double.MIN_VALUE
loop n_ = 0 to dlist.length - 1
if dlist[n_] > dmax then dmax = dlist[n_]
end n_
return dmax
 
method getMax(dlist = Rexx[]) public static binary returns Rexx
dmax = Rexx(Double.MIN_VALUE)
loop n_ = 0 to dlist.length - 1
dmax = dlist[n_].max(dmax)
end n_
return dmax
 
Output:
Max double:  274.457568703
Max   Rexx:  274.457568703

[edit] NewLISP

(max 1 2 3 5 2 3 4)

[edit] Nial

The behavior of multi-dimensional arrays is like J

max 1 2 3 4
=4

[edit] Nimrod

echo max([2,3,4,5,6,1])
Output:
6

[edit] Objeck

The language has a "Max" method for vectors.

 
values := IntVector->New([4, 1, 42, 5]);
values->Max()->PrintLine();
 

[edit] Objective-C

Works with: GNUstep
Works with: Cocoa

This code "extends" (through Objective-C categories) the NSArray adding the method maximumValue; this one iterates over the objects of the collection calling the method compare, if it exists for the object of the collection. Since normally comparing makes sense between numbers, the code also check if the objects being compared are of "kind" NSNumber. If one eliminates this check (substituting it maybe with one that checks if the two object are of the same "kind"), the code is able to get a maximum value for any objects for which make sense a compare method (e.g. strings), that must be implemented.

If there's no a known way of comparing two objects of the collection (or if the objects are not "NSNumber"), the the method return nil (the void object).


#import <Foundation/Foundation.h>
 
@interface NSArray (WithMaximum)
- (id)maximumValue;
@end
 
@implementation NSArray (WithMaximum)
- (id)maximumValue
{
if ( [self count] == 0 ) return nil;
id maybeMax = self[0];
for ( id el in self ) {
if ( [maybeMax respondsToSelector: @selector(compare:)] &&
[el respondsToSelector: @selector(compare:)] &&
[el isKindOfClass: [NSNumber class]] &&
[maybeMax isKindOfClass: [NSNumber class]] ) {
if ( [maybeMax compare: el] == NSOrderedAscending )
maybeMax = el;
} else { return nil; }
}
return maybeMax;
}
@end

This example mixes integers with a double value, just to show that everything is fine until they are NSNumber.

int main()
{
@autoreleasepool {
NSArray *collection = @[@1, @2, @10, @5, @10.5];
 
NSLog(@"%@", [collection maximumValue]);
}
return 0;
}

[edit] OCaml

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

[edit] Octave

Octave's max accepts a vector (and can return also the index of the maximum value in the vector)

m = max( [1,2,3,20,10,9,8] );       % m = 20
[m, im] = max( [1,2,3,20,10,9,8] ); % im = 4

[edit] ooRexx

[edit] version

 
-- routine that will work with any ordered collection or sets and bags containing numbers.
::routine listMax
use arg list
items list~makearray -- since we're dealing with different collection types, reduce to an array
if items~isEmpty then return .nil -- return a failure indicator. could also raise an error, if desired
largest = items[1]
 
 
-- note, this method does call max one extra time. This could also use the
-- do i = 2 to items~size to avoid this
do item over items
largest = max(item, largest)
end
 
return largest
 

[edit] version 2 works with any strings

/* REXX ***************************************************************
* 30.07.2013 Walter Pachl as for REXX
**********************************************************************/
s=.list~of('Walter','lives','in','Vienna')
say listMax(s)
-- routine that will work with any ordered collection or sets and bags.
::routine listMax
use arg list
items=list~makearray -- since we're dealing with different collection types, reduce to an array
if items~isEmpty then return .nil -- return a failure indicator. could also raise an error, if desired
largest = items[1]
-- note, this method uses one extra comparison. It could use
-- do i = 2 to items~size to avoid this
do item over items
If item>>largest Then
largest = item
end
return largest

[edit] Oz

declare
fun {Maximum X|Xr} %% pattern-match on argument to make sure the list is not empty
{FoldL Xr Value.max X} %% fold the binary function Value.max over the list
end
in
{Show {Maximum [1 2 3 4 3]}}

[edit] PARI/GP

vecmax(v)

[edit] Pascal

See Delphi

[edit] Perl

sub max {
my $max = shift;
for (@_) { $max = $_ if $_ > $max }
return $max;
}

It is already implemented in the module List::Util's max() function:

use List::Util qw(max);
 
max(@values);

[edit] Perl 6

The built-in function works with any type that defines ordering.

say max 10, 4, 5, -2, 11;
say max <zero one two three four five six seven eight nine>;
Output:
11
zero

[edit] PHP

The built-in PHP function max() already does this.

max($values)

[edit] PicoLisp

: (max 2 4 1 3)               # Return the maximal argument
-> 4
: (apply max (2 4 1 3)) # Apply to a list
-> 4
: (maxi abs (2 -4 -1 3)) # Maximum according to given function
-> -4

[edit] PL/I

 
maximum = A(lbound(A,1));
do i = lbound(A,1)+1 to hbound(A,1);
if maximum < A(i) then maximum = A(i);
end;
 

[edit] PostScript

Ghostscript has a max built-in:

Works with: Ghostscript
/findmax {
dup 0 get exch  % put the first element underneath the array
{max} forall  % replace it by the respective larger value if necessary
} def

If not using Ghostscript this gets a bit longer:

/findmax {
dup 0 get exch  % put the first element underneath the array
{
dup  % duplicate the current item
2 index  % duplicate the current maximum value
gt  % if the current item is larger
{exch} if  % swap the two items so the previous maximum is now the top of the stack
pop  % remove it
} forall
} def
Library: initlib
 
[1 2 3 4 5 4 3 2 1] uncons exch {max} fold
 

[edit] PowerBASIC

FUNCTION PBMAIN()
DIM x AS LONG, y AS LONG, z AS LONG
RANDOMIZE TIMER
 
FOR x = 1 TO 10
y = INT(RND * 10000)
z = MAX(y, z)
NEXT
 
 ? STR$(z) & " was the highest value"
END FUNCTION
Output:
 8104 was the highest value

[edit] PowerShell

The Measure-Object cmdlet in PowerShell already has this capability:

function Get-Maximum ($a) {
return ($a | Measure-Object -Maximum).Maximum
}

[edit] Prolog

SWI-Prolog already knows max_list.

 ?- max_list([1, 2, 10, 3, 0, 7, 9, 5], M).
M = 10.

can be implemented like this:

max_list(L, V) :-
select(V, L, R), \+((member(X, R), X > V)).
 

[edit] PureBasic

Procedure.f Max (Array a.f(1))
Protected last, i, ret.f
 
ret = a(0)
last = ArraySize(a())
For i = 1 To last
If ret < a(i)
ret = a(i)
EndIf
Next
 
ProcedureReturn ret
EndProcedure

[edit] Python

The built-in Python function max() already does this.

max(values)

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

>>> floatstrings = ['1\n', ' 2.3\n', '4.5e-1\n', '0.01e4\n', '-1.2']
>>> max(floatstrings, key = float)
'0.01e4\n'
>>>

Normally we would want the converted form as the maximum and we could just as easily write:

>>> max(float(x) for x in floatstrings)
100.0
>>>

[edit] R

v <- c(1, 2, 100, 50, 0)
print(max(v)) # 100

[edit] Racket

The "max" function it built in and takes an arbitrary amount of arguments.

(max 12 9 8 17 1)
Output:
17

To use with a list, there is apply:

(apply max '(12 9 8 17 1))

However, if you want to write the function yourself:

 
(define (my-max l)
(define (max-h l greatest)
(cond [(empty? l) greatest]
[(> (first l) greatest) (max-h (rest l) (first l))]
[else (max-h (rest l) greatest)]))
(if (empty? l) empty (max-h l (first l))))
 

or with a "for" loop:

 
(define (my-max l)
(for/fold ([max #f]) ([x l])
(if (and max (> max x)) max x)))
 

[edit] RapidQ

functioni FindMax(...) as double
dim x as integer
 
for x = 1 to ParamValCount
IF ParamVal(x) > Result THEN Result = ParamVal(x)
next
End functioni
 
Print FindMax(50, 20, 65, 20, 105)
 

[edit] Rascal

Rascal has a built-in function that gives the greatest element of a list

 
rascal>import List;
ok
 
rascal>max([1,2,3,4]);
int: 4
 


[edit] Raven

[ 1 2 3 4 ] max "%d\n" print
Output:
4

Randomly generated list size and elements

100 choose as $cnt
[ ] as $lst
0 $cnt 1 range each drop 100 choose $lst push
$lst print
$lst max "max value: %d\n" print

[edit] REBOL

rebol [
Title: "Maximum Value"
Date: 2009-12-15
Author: oofoe
URL: http://rosettacode.org/wiki/Maximum_Value
]

 
max: func [
"Find maximum value in a list."
values [series!] "List of values."
] [
first maximum-of values
]
 
print ["Max of" mold d: [5 4 3 2 1] "is" max d]
print ["Max of" mold d: [-5 -4 -3 -2 -1] "is" max d]
Output:
Max of [5 4 3 2 1] is 5
Max of [-5 -4 -3 -2 -1] is -1

[edit] REXX

The numbers in the list may be any valid REXX number   (integer, negative, floating point, etc.)

[edit] using a list

/*REXX program finds the  greatest element  in a list  (of numbers).    */
/* [↓] list of first twenty reversed primes*/
y = 2 3 5 7 11 31 71 91 32 92 13 73 14 34 74 35 95 16 76 17
big=word(y,1) /*choose a initial biggest number*/
do j=2 to words(y) /*traipse through the list. */
big=max(big, word(y,j)) /*use the MAX bif to find biggie.*/
end /*j*/
 
say 'the biggest value in a list of ' words(y) " numbers is: " big
/* [↓] list of first twenty reversed primes*/
/*stick a fork in it, we're done.*/
Output:
the biggest value in a list of  20  numbers is:  95

[edit] using an array

/*REXX program finds the  greatest element  in an array (of numbers).   */
y.= /*set all array elements to null.*/
y.1 = 2; y.2 = 3; y.3 = 5; y.4 = 7; y.5 = 11
y.6 = 31; y.7 = 71; y.8 = 91; y.9 = 32; y.10 = 92
y.11 = 13; y.12 = 73; y.13 = 14; y.14 = 34; y.15 = 74
y.16 = 35; y.17 = 95; y.18 = 16; y.19 = 76; y.20 = 17
 
big = y.1 /*choose a initial biggest number*/
do j=2 while y.j\=='' /*traipse through the whole array*/
big = max(big, y.j) /*use a BIF to find the biggie.*/
end /*j*/
 
say 'the biggest value in an array of ' j-1 " elements is: " big
/*stick a fork in it, we're done.*/
Output:
the biggest value in an array of  20  elements is:  95

[edit] using a list from console

/*REXX program finds the  greatest element  in an array (of numbers).   */
say 'Please enter a list of numbers (separated by blanks or commas):'
parse pull nums /*get a list from console (user).*/
nums=translate(nums,,',') /*change commas (,) to blanks.*/
items=words(nums) /*obtain the number of numbers. */
big=word(nums,1) /*assume the biggest is the 1st #*/
 
do j=2 to items /*traipse through the list. */
big = max(big, word(nums,j) ) /*use a BIF for finding the max. */
end /*j*/
 
say 'the biggest value in the list of ' items " elements is: " big
/*stick a fork in it, we're done.*/

[edit] list of any strings

/* REXX ***************************************************************
* If the list contains any character strings, the following will wotk
* Note the use of >> (instead of >) to avoid numeric comparison
* 30.07.2013 Walter Pachl
**********************************************************************/

list='Walter Pachl living in Vienna'
Say max(list)
list='8 33 -12'
Say max(list)
Exit
max: Procedure
Parse Arg l
max=word(l,1)
Do i=2 To words(l)
If word(l,i)>>max Then
max=word(l,i)
End
Return max
Output:
(PC):
living
8    

output when using a list which is:   12 111111 1 (lexigraphically 12 is greater than 111111)

12

[edit] Ruby

max is a method of all Enumerables

values.max

[edit] Run BASIC

list$= "1 12 -55 46 41 3.66 19"
while word$(list$,i+1," ") <> ""
mx = max(mx,val(word$(list$,i+1," ")))
i = i + 1
wend
print mx

[edit] Scala

Library: Scala
def noSweat(list: Int*) = list.max
// Test
assert(noSweat(1, 3, 12, 7) == 12)

[edit] Scheme

The built-in Scheme function max takes the max of all its arguments.

(max 1 2 3 4)
(apply max values) ; find max of a list

[edit] Seed7

$ include "seed7_05.s7i";
 
const func integer: max (in array integer: values) is func
result
var integer: max is 0;
local
var integer: index is 0;
begin
max := values[1];
for index range 2 to length(values) do
if values[index] > max then
max := values[index];
end if;
end for;
end func;
 
const proc: main is func
begin
writeln(max([] (1, 2, 6, 4, 3)));
end func;
Output:
6

[edit] Sidef

max method returns the greatest element in a list. It works only if the array's elements have the same type (e.g.: strings, numbers).

values.max;

[edit] Slate

#(1 2 3 4 20 10 9 8) reduce: [| :a :b | a max: b]

[edit] Smalltalk

Using fold it is very simple to find the maximum value among a collection.

#(1 2 3 4 20 10 9 8) fold: [:a :b | a max: b] "returns 20"

Or, since it's "built-in", you can simply do:

Works with: Pharo version 1.4
Works with: Smalltalk/X
#(1 2 3 4 20 10 9 8) max. "returns 20"

[edit] SNOBOL4

while   a = trim(input)     :f(stop)
max = gt(a,max) a  :(while)
stop output = max
end

[edit] Standard ML

Comparisons are specific for each type. Here is a max function for a list of ints:

fun max_of_ints [] = raise Empty
| max_of_ints (x::xs) = foldl Int.max x xs
- max_of_ints [4,3,5,9,2,3];
val it = 9 : int

[edit] Swift

let x = maxElement([4,3,5,9,2,3])
println(x) // prints 9

[edit] Tcl

Works with: Tcl version 8.5

Use the {*} expansion operator to substitute the list value with its constituent elements

package require Tcl 8.5
 
set values {4 3 2 7 8 9}
::tcl::mathfunc::max {*}$values ;# ==> 9

[edit] TI-89 BASIC

The builtin max function can be applied to lists. max({1, 3, 2}) = 3.

[edit] Trith

[1 -2 3.1415 0 42 7] [max] foldl1

[edit] TUSCRIPT

 
$$ MODE TUSCRIPT
LOOP n,list="2'4'0'3'1'2'-12"
IF (n==1) greatest=VALUE(list)
IF (list>greatest) greatest=VALUE(list)
ENDLOOP
PRINT greatest
 
Output:
4

[edit] UNIX Shell

Works with: bash version 3
Works with: pdksh
max() {
local m=$1
shift
while [ $# -gt 0 ]
do
[ "$m" -lt "$1" ] && m=$1
shift
done
echo "$m"
}
 
max 10 9 11 57 1 12
Works with: Bourne Shell
max() {
m=$1 # Bourne Shell has no local command.
shift
while [ $# -gt 0 ]
do
[ "$m" -lt "$1" ] && m=$1
shift
done
echo "$m"
}

[edit] Ursala

The built-in $^ operator takes a binary predicate of any type to a function extracting the maximum value from a non-empty list of that type. In this case it is used with fleq, the partial order relation on floating point numbers.

#import flo
 
#cast %e
 
example = fleq$^ <-1.,-2.,0.,5.,4.,6.,1.,-5.>
Output:
6.000000e+00

[edit] 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

[edit] Vim Script

for numbers (not floats):

max([1, 3, 2])

result: 3

for strings (with configurable ignore-case):

function! Max(list, ...)
" {list} list of strings

" {a:1} 'i': ignore case, 'I': match case, otherwise use 'ignorecase' option

if empty(a:list)
return 0
endif
let gt_op = a:0>=1 ? get({'i': '>?', 'I': '>#'}, a:1, '>') : '>'
let cmp_expr = printf('a:list[idx] %s maxval', gt_op)
let maxval = a:list[0]
let len = len(a:list)
let idx = 1
while idx < len
if eval(cmp_expr)
let maxval = a:list[idx]
endif
let idx += 1
endwhile
return maxval
endfunction

[edit] Visual Basic

Public Function ListMax(anArray())
'return the greatest element in array anArray
'use LBound and UBound to find its length
n0 = LBound(anArray)
n = UBound(anArray)
theMax = anArray(n0)
For i = (n0 + 1) To n
If anArray(i) > theMax Then theMax = anArray(i)
Next
ListMax = theMax
End Function
 
 
Public Sub ListMaxTest()
Dim b()
'test function ListMax
'fill array b with some numbers:
b = Array(5992424433449#, 4534344439984#, 551344678, 99800000#)
'print the greatest element
Debug.Print "Greatest element is"; ListMax(b())
End Sub

Result:

ListMaxTest
Greatest element is 5992424433449

[edit] Wart

Wart defines max in terms of the more general best.

def (best f seq)
if seq
ret winner car.seq
each elem cdr.seq
if (f elem winner)
winner <- elem
 
def (max ... args)
(best (>) args)

(>) is > suppressing infix expansion.

[edit] Wortel

The @maxl returns the maximum value of a list:

@maxl [1 6 4 6 4 8 6 3] ; returns 8

[edit] XPL0

The set of values is the lengths of the lines of text in the input file.

include c:\cxpl\codes;                  \include 'code' declarations
 
def Tab=$09, LF=$0A, CR=$0D, EOF=$1A;
 
int CpuReg, Hand;
char CmdTail($80);
int I, Max, C;
 
[\Copy file name on command line, which is in the Program Segment Prefix (PSP)
\ ES=CpuReg(11), to the CmdTail array, which is in our Data Segment = CpuReg(12)
CpuReg:= GetReg; \point to copy of CPU registers
Blit(CpuReg(11), $81, CpuReg(12), CmdTail, $7F);
Hand:= FOpen(CmdTail, 0); \open file for input and get its handle
FSet(Hand, ^I); \assign handle to device 3
OpenI(3); \initialize file for input
 
Max:= 0; \scan file for longest line
repeat I:= 0;
repeat C:= ChIn(3);
case C of
CR, LF, EOF: []; \don't count these characters
Tab: [I:= I+8 & ~7] \(every 8th column)
other I:= I+1; \count all other characters
until C=LF or C=EOF;
if I > Max then Max:= I;
until C = EOF;
Text(0, "Longest line = "); IntOut(0, Max); CrLf(0);
]

Example of running the program on its source code:

maxline maxline.xpl
Longest line = 80

[edit] XSLT

The desired value is the first in a sequence that has been sorted numerically in descending order.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
 
<xsl:template match="/">
<xsl:for-each select="/*/*">
<!-- without data-type="number", items are sorted alphabetically -->
<xsl:sort data-type="number" order="descending"/>
<xsl:if test="position() = 1">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Sample input:

<numbers>
<number>3</number>
<number>1</number>
<number>12</number>
<number>7</number>
</numbers>
Output:
 12

[edit] Yorick

The built-in function max does this. Interactive example:

> foo = [4, 3, 2, 7, 8, 9]
> max(foo)
9

[edit] zkl

(1).max(1,2,3)     //-->3
(66).max(1,2,3.14) //-->66

If given a list, the max of the list is returned. The number/object just selects the method to call. Notice the difference between Int.max and Float.max.

(66).max(T(1,2,3)) //-->3
(66).max(T(1,2,3.14)) //-->3
(6.6).max(T(1,2,3.14)) //-->3.14

For other object types, you could use:

fcn max{ vm.arglist.reduce(fcn(p,n){ if(p < n) n else p }) }
max(2,1,-40,50,2,4,2) //-->50
max(2) //-->2
max("foo","bar") //-->"foo"
max("3",4,"5") //-->"5" only if strings contain only digits
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox