Greatest element of a list: Difference between revisions

no edit summary
(→‎JS ES6: Updated primitives, tidied.)
imported>Lacika7
No edit summary
 
(31 intermediate revisions by 23 users not shown)
Line 9:
=={{header|11l}}==
11l already has a "Maximum Value" function.
<syntaxhighlight lang ="11l">max(values)</langsyntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
[ 1.0, 2.3, 1.1, 5.0, 3, 2.8, 2.01, 3.14159 ] ' n:max 0 a:reduce . cr
</syntaxhighlight>
</lang>
Output: 5
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program rechMax64.s */
Line 140:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 147:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun maximum (xs)
(if (endp (rest xs))
(first xs)
(max (first xs)
(maximum (rest xs)))))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC Max(BYTE ARRAY tab BYTE size)
BYTE i,res
 
Line 184:
m=Max(tab,size)
PrintF("Greatest: %I%E",m)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Greatest_element_of_a_list.png Screenshot from Atari 8-bit computer]
Line 193:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function max(... args):Number
{
var curMax:Number = -Infinity;
Line 199:
curMax = Math.max(curMax, args[i]);
return curMax;
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="ada">with Ada.Text_Io;
 
procedure Max_Test isco
Line 230:
begin
Ada.Text_IO.Put_Line(Float'Image(Max(Buf)));
end Max_Test;</langsyntaxhighlight>
A generic function Max to deal with any floating-point type.
<langsyntaxhighlight lang="ada">generic
type Item is digits <>;
type Items_Array is array (Positive range <>) of Item;
function Generic_Max (List : Items_Array) return Item;</langsyntaxhighlight>
Implementation of:
<langsyntaxhighlight lang="ada">function Generic_Max (List : Items_Array) return Item is
Result : Item := List (List'First);
begin
Line 244:
end loop;
return Result;
end Generic_Max;</langsyntaxhighlight>
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.
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer
lmax(list l)
{
Line 262:
 
max;
}</langsyntaxhighlight>
or
<langsyntaxhighlight lang="aime">integer
lmax(list l)
{
Line 273:
 
max;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 280:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68"># substitute any array type with a scalar element #
MODE FLT = REAL;
 
Line 309:
except empty array:
SKIP
)</langsyntaxhighlight>
{{out}}
<pre>
Line 316:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% simple list type %
record IntList( integer val; reference(IntList) next );
Line 342:
write( maxElement( IntList( -767, IntList( 2397, IntList( 204, null ) ) ) ) )
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 350:
=={{header|Amazing Hopper}}==
Version 1:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
main:
Line 369:
{"\n"} print
exit(0)
</syntaxhighlight>
</lang>
Version 2:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
#define SIZE_LIST 100000
Line 387:
{"\n"} print
exit(0)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 394:
 
=={{header|AntLang}}==
<syntaxhighlight lang AntLang="antlang">max|range[10]</langsyntaxhighlight>
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl">LIST←2 4 6 3 8
⌈/LIST</langsyntaxhighlight>
{{out}} <pre>8</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">
<lang AppleScript>
max({1, 2, 3, 4, 20, 6, 11, 3, 9, 7})
 
Line 412:
return _curMax
end max
</syntaxhighlight>
</lang>
 
 
Line 419:
{{trans|JavaScript}}
 
<syntaxhighlight lang="applescript">
<lang AppleScript>
-- maximumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a
on maximumByMay(f, xs)
Line 569:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{"epsilon", {name:"Shanghai", population:24.15}}</langsyntaxhighlight>
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBASIClang="applesoftbasic"> 100 REMMAX
110 R$ = "":E$ = ""
120 L = LEN (L$)
Line 593:
270 R = VAL (V$)
280 IF R < V THEN RETURN
290 R$ = V$: RETURN</langsyntaxhighlight>
<langsyntaxhighlight ApplesoftBASIClang="applesoftbasic">L$ = "1 2 3 4 20 6 11 3 9 7"
GOSUB 100MAX
PRINT R$</langsyntaxhighlight>
{{Out}}
<pre>20</pre>
Line 602:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 815:
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">arr: [5 4 2 9 7 3]
 
print max arr</langsyntaxhighlight>
{{out}}
Line 828:
=={{header|AutoHotkey}}==
=== CSV Data ===
<langsyntaxhighlight AutoHotkeylang="autohotkey">list = 1,5,17,-2
Loop Parse, list, `,
x := x < A_LoopField ? A_LoopField : x
MsgBox Max = %x%</langsyntaxhighlight>
=== Pseudo-arrays ===
<langsyntaxhighlight AHKlang="ahk">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%</langsyntaxhighlight>
=== True arrays ===
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AHKlang="ahk">List := [1,5,17,-2]
For each, value in List
x := x < value ? value : x
MsgBox Max = %x%</langsyntaxhighlight>
 
=={{header|AWK}}==
One-liner:
<langsyntaxhighlight lang="awk">$ 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</langsyntaxhighlight>
 
More readable version:
<langsyntaxhighlight lang="awk">
# Usage: awk -f greatest_list_element.awk
#
Line 864:
print max(a)
}
</syntaxhighlight>
</lang>
 
=={{header|Axe}}==
This example assumes the array is null-terminated so that the program can stop at the end of the data.
<langsyntaxhighlight lang="axe">Lbl MAX
0→M
While {r₁}
Line 874:
End
M
Return</langsyntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QBasic}}
 
<langsyntaxhighlight lang="qbasic">DECLARE SUB addVal (value AS INTEGER)
DECLARE FUNCTION findMax% ()
 
Line 924:
NEXT
findMax = tmp2
END FUNCTION</langsyntaxhighlight>
 
{{Out}}
Line 932:
 
==={{header|BaCon}}===
<langsyntaxhighlight lang="freebasic">' Greatest element from list
' Populate sample array of numbers
READ elements
Line 953:
NEXT
RETURN mx
END FUNCTION</langsyntaxhighlight>
 
{{out}}
Line 961:
'''See also:''' [[#BBC BASIC|BBC BASIC]], [[#Liberty BASIC|Liberty BASIC]], [[#PowerBASIC|PowerBASIC]], [[#PureBasic|PureBasic]], [[#Run BASIC|Run BASIC]], [[#TI-89 BASIC|TI-89 BASIC]], [[#Visual Basic|Visual Basic]]
 
==={{header|BASIC256}}===
{{trans|Yabasic}}
<langsyntaxhighlight lang="freebasic">l$ = "1,1234,62,234,12,34,6"
dim n$(1)
n$ = explode(l$, ",")
Line 974:
next i
 
print "Alphabetic order: "; m$; ", numeric order: "; m</langsyntaxhighlight>
 
==={{header|Chipmunk Basic}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|Minimal BASIC}}===
{{trans|Quite BASIC}}
<syntaxhighlight lang="qbasic">10 PRINT "HOW MANY ITEMS? "
20 INPUT N
30 FOR J = 0 TO N-1
40 PRINT "VALUE OF ITEM #";J
50 INPUT T
60 LET A(J) = T
70 NEXT J
80 LET C = A(0)
90 LET I = 0
100 FOR J = 1 TO N-1
110 IF A(J) > C THEN 130
120 GOTO 150
130 LET C = A(J)
140 LET I = J
150 NEXT J
160 PRINT "THE MAXIMUM VALUE WAS ";C;" AT INDEX ";I;"."
170 END</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">1000 DEF FINDMAX(REF ARR)
1010 LET MX=ARR(LBOUND(ARR))
1020 FOR I=LBOUND(ARR)+1 TO UBOUND(ARR)
1030 LET MX=MAX(MX,ARR(I))
1040 NEXT
1050 LET FINDMAX=MX
1060 END DEF</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
{{trans|GW-BASIC}}
<syntaxhighlight lang="qbasic">10 INPUT "How many items"; N%
20 DIM ARR(N%)
30 FOR I% = 0 TO N% - 1
40 PRINT "Value of item #"; I%
50 INPUT ARR(I%)
60 NEXT I%
70 CHAMP = ARR(0) : INDEX = 0
80 FOR I% = 1 TO N% - 1
90 IF ARR(I%) > CHAMP THEN CHAMP = ARR(I%): INDEX = I%
100 NEXT I%
110 PRINT "The maximum value was "; CHAMP; " at index "; INDEX; "."
120 END</syntaxhighlight>
 
==={{header|Quite BASIC}}===
{{trans|GW-BASIC}}
<syntaxhighlight lang="qbasic">10 INPUT "How many items? "; n
20 ARRAY a
30 FOR j = 0 TO n-1
40 PRINT "Value of item #"; j
50 INPUT ""; t
60 LET a(j) = t
70 NEXT j
80 LET c = a(0)
90 LET i = 0
100 FOR j = 1 TO n-1
110 IF a(j) > c THEN LET c = a(j) : LET i = j
120 NEXT j
130 PRINT "The maximum value was "; c; " at index "; i; "."
140 END</syntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">::max.cmd
@echo off
setlocal enabledelayedexpansion
Line 993 ⟶ 1,058:
if "%2" equ "" goto :eof
if %2 gtr !%1! set res=%2
goto loop</langsyntaxhighlight>
 
''Invocation from command line or from internal prompt''
 
<langsyntaxhighlight lang="dos">>max "123 456 3 234243 12"
234243
 
>max
Input stream: 5 4 3 2 67 1
67</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> ListOfValues$ = "13, 0, -6, 2, 37, -10, 12"
PRINT "Maximum value = " ; FNmax(ListOfValues$)
END
Line 1,017 ⟶ 1,082:
IF number > max THEN max = number
UNTIL index% = 0
= max</langsyntaxhighlight>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">define m(a[], n) {
auto m, i
 
Line 1,028 ⟶ 1,093:
}
return(m)
}</langsyntaxhighlight>
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">001pv <
>&:01g`#v_1+#^_01g.@
^p10 <</langsyntaxhighlight>
Only works with positive integers. List must be terminated with -1.
 
=={{header|BQN}}==
<syntaxhighlight lang ="bqn">Max ← ⌈´</langsyntaxhighlight>
 
{{out}}
Line 1,048 ⟶ 1,113:
=={{header|Bracmat}}==
When comparing two rational numbers, Bracmat compares numerically. In all other cases Bracmat compares lexically.
<syntaxhighlight lang="text"> ( biggest
= max
. !arg:
Line 1,061 ⟶ 1,126:
biggest
$ (5 100000 -5 43756243978569758/13 3365864921428443 87512487957139516/27 3446)
)</langsyntaxhighlight>
{{Out}}
<pre>1: mies
Line 1,069 ⟶ 1,134:
=={{header|Brat}}==
Arrays have a max function, but here's a manual implementation.
<langsyntaxhighlight lang="brat">max = { list |
list.reduce { n, max |
true? n > max
Line 1,077 ⟶ 1,142:
}
 
p max [3 4 1 2]</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) {88 99 77 66 55}>]
99
</syntaxhighlight>
</lang>
 
=={{header|C}}==
This works well with floats. Replace with double, int or what-have-you before passing a different data type.
<langsyntaxhighlight lang="c">#include <assert.h>
 
float max(unsigned int count, float values[]) {
Line 1,098 ⟶ 1,163:
}
return themax;
}</langsyntaxhighlight>
 
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). <!-- You might wanna look at the macro from here which can count the number of arguments without parsing commas: http://groups.google.com/group/comp.std.c/browse_thread/thread/77ee8c8f92e4a3fb/346fc464319b1ee5 -->
 
{{works with|GCC}}
<langsyntaxhighlight lang="c">#include <stdarg.h>
 
#define MAX(A,...) ({ inline __typeof__ (A) _max_(__typeof__ (A) a, ...) {\
Line 1,116 ⟶ 1,181:
}\
_max_((A),__VA_ARGS__);\
})</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 1,122 ⟶ 1,187:
C# already has a "Maximum Value" function.
 
<langsyntaxhighlight lang="csharp">int[] values = new int[] {1,2,3,4,5,6,7,8,9,10};
 
int max = values.Max();</langsyntaxhighlight>
 
=={{header|C++}}==
A simple wrapper around the standard library function <tt>max_element()</tt>.
Requires C++17.
<langsyntaxhighlight lang="cpp">#include <algorithm> //std::max_element
#include <iterator> //std::begin and std::end
#include <functional> //std::less
Line 1,148 ⟶ 1,213:
using std::begin; using std::end;
return max_value(begin(container), end(container), compare);
}</langsyntaxhighlight>
 
=={{header|CFEngine}}==
Line 1,154 ⟶ 1,219:
Note: CFEngine bundles are NOT functions, however they can behave in some ways that are similar to functions.
 
<langsyntaxhighlight lang="cfengine3">
bundle agent __main__
{
Line 1,190 ⟶ 1,255:
bundle_return_value_index => "max";
}
</syntaxhighlight>
</lang>
 
{{output}}
Line 1,199 ⟶ 1,264:
=={{header|Clojure}}==
The Clojure.core function max returns the max of its arguments.
<langsyntaxhighlight lang="clojure">(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</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% This "maximum" procedure is fully general, as long as
% the container type has an elements iterator and the
% data type is comparable.
Line 1,242 ⟶ 1,307:
rmax: real := maximum[sequence[real], real](reals)
stream$putl(po, "maximum real: " || real$unparse(rmax))
end start_up</langsyntaxhighlight>
 
{{out}}
Line 1,251 ⟶ 1,316:
Only for lists of integers.
 
<langsyntaxhighlight lang="cmake"># 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)
Line 1,269 ⟶ 1,334:
set(list 33 11 44 22 66 55)
max(maximum ${list})
message(STATUS "maximum of ${list} => ${maximum}")</langsyntaxhighlight>
 
<pre>-- maximum of 33;11;44;22;66;55 => 66</pre>
Line 1,275 ⟶ 1,340:
=={{header|COBOL}}==
This is already built into the language for tables of numbers.
<langsyntaxhighlight lang="cobol">DISPLAY FUNCTION MAX(nums (ALL))</langsyntaxhighlight>
 
A sample implementation:
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
FUNCTION-ID. greatest-elt.
 
Line 1,302 ⟶ 1,367:
GOBACK
.
END FUNCTION greatest-elt.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
# using Math library
max1 = (list) ->
Line 1,322 ⟶ 1,387:
a = [0,1,2,5,4];
alert(max1(a)+". The answer is "+max2(a));
</syntaxhighlight>
</lang>
 
=={{header|ColdFusion}}==
<langsyntaxhighlight lang="cfm">
<Cfset theList = '1, 1000, 250, 13'>
<Cfparam name="maxNum" default=0>
Line 1,332 ⟶ 1,397:
</Cfloop>
<Cfoutput>#maxNum#</Cfoutput>
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="cfm">
<Cfset theList = '1, 1000, 250, 13'>
<Cfset maxNum = ListFirst(ListSort(thelist, "numeric", "desc"))>
<Cfoutput>#maxNum#</Cfoutput>
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
The built-in Common Lisp function <tt>max</tt> takes the max of all its arguments.
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BalckBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Operations;
IMPORT StdLog,Args,Strings;
Line 1,383 ⟶ 1,448:
 
END Operations.
</syntaxhighlight>
</lang>
Execute: ^Q Operations..DoMax 23 12 3 45 34 54 84 ~<br/>
{{Out}}
Line 1,391 ⟶ 1,456:
 
=={{header|Crystal}}==
<syntaxhighlight lang ="ruby">values.max</langsyntaxhighlight>
 
=={{header|D}}==
Line 1,397 ⟶ 1,462:
D already has a "Maximum Element" function.
 
<langsyntaxhighlight lang="d">void main()
{
import std.algorithm.searching : maxElement;
Line 1,403 ⟶ 1,468:
 
[9, 4, 3, 8, 5].maxElement.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>9</pre>
 
=={{header|Dart}}==
<langsyntaxhighlight Dartlang="dart">/*This is a function which returns the greatest element in a list of numbers */
num findGreatestElement(List<num> list){
num greatestElement = list[0];
Line 1,423 ⟶ 1,488:
return list.reduce(max);
}
</syntaxhighlight>
</lang>
 
=={{header|dc}}==
<langsyntaxhighlight lang="dc">[sm llx] sg
[lm p q] sq
[d lm <u s_ z 0 =q llx] sl
Line 1,437 ⟶ 1,502:
_275.0 _111.19 0.0 _1234568.0 lp lp _1 *
 
lgx</langsyntaxhighlight>
 
{{Out}}
Line 1,443 ⟶ 1,508:
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ list = "45,65,81,12,0,13,-56,123,-123,888,12,0"
$ max = f$integer( f$element( 0, ",", list ))
$ i = 1
Line 1,454 ⟶ 1,519:
$ goto loop
$ done:
$ show symbol max</langsyntaxhighlight>
{{out}}
<pre>$ @greatest
Line 1,460 ⟶ 1,525:
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
program GElemLIst;
{$IFNDEF FPC}
Line 1,484 ⟶ 1,549:
writeln(Math.MaxValue(fltArr));
end.
</syntaxhighlight>
</lang>
 
=={{header|Dyalect}}==
<langsyntaxhighlight lang="dyalect">func max(xs) {
var y
for x in xs {
Line 1,498 ⟶ 1,563:
var xs = [1..10]
max(xs)</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">max lst:
lst! 0
for item in copy lst:
Line 1,507 ⟶ 1,572:
item drop
 
!. max [ 10 300 999 9 ]</langsyntaxhighlight>
{{out}}
<pre>999</pre>
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">/* Find the greatest element in an array of ints */
proc nonrec max([*] int a) int:
int INT_MIN = ~((~0) >> 1);
Line 1,527 ⟶ 1,592:
type arr = [8] int;
writeln("Maximum: ", max(arr(1,5,17,2,53,99,61,3)))
corp</langsyntaxhighlight>
{{out}}
<pre>Maximum: 99</pre>
Line 1,535 ⟶ 1,600:
This function works for any value which responds to <code>[http://wiki.erights.org/wiki/Category:Message_max/1 max/1]</code>:
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator") # non-finalized syntax feature
 
def max([first] + rest) {
return accum first for x in rest { _.max(x) }
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? max([1, 2, 3])
# value: 3</langsyntaxhighlight>
 
To require only the comparison protocol, one needs to write out the algorithm a little more explicitly:
 
<langsyntaxhighlight lang="e">def max([var bestSoFar] + rest) {
for x ? (x > bestSoFar) in rest {
bestSoFar := x
}
return bestSoFar
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? max([1, 3, 2])
# value: 3
 
? max([[1].asSet(), [2].asSet(), [1, 2].asSet()])
# value: [1, 2].asSet()</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">a[] = [ 2 9 4 3 8 5 ]
for e in a[]
max = higher e max
.
print max</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;; a random length list of random values
(define L (map random (make-list (random 50) 100))) → L
Line 1,575 ⟶ 1,640:
;; find max
(apply max L) → 97
</syntaxhighlight>
</lang>
 
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
<lang ECL>
MaxVal(SET OF INTEGER s) := MAX(s);
 
Line 1,585 ⟶ 1,650:
SetVals := [4,8,16,2,1];
MaxVal(SetVals) //returns 16;
</syntaxhighlight>
</lang>
 
=={{header|Efene}}==
 
<langsyntaxhighlight lang="efene">list_max = fn ([Head:Rest]) {
list_max(Rest, Head)
}
Line 1,612 ⟶ 1,677:
io.format("~p~n", [list_max1([9, 4, 3, 8, 5])])
}
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
The GREATEST_ELEMENT class:
<langsyntaxhighlight lang="eiffel">
class
GREATEST_ELEMENT [G -> COMPARABLE]
Line 1,657 ⟶ 1,722:
 
end
</syntaxhighlight>
</lang>
A test application:
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,680 ⟶ 1,745:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
 
<langsyntaxhighlight lang="ela">open list
 
findBy p (x::xs) = foldl (\x y | p x y -> x | else -> y) x xs
maximum = findBy (>)
 
maximum [1..10]</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
extension op
Line 1,704 ⟶ 1,769:
while (en.next())
{
var item := *en.get();
if (nil == maximal)
{
Line 1,722 ⟶ 1,787:
{
console.printLine(new int[]{1,2,3,4,20,10,9,8}.Maximal)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,729 ⟶ 1,794:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> Enum.max([3,1,4,1,5,9,2,6,5,3])
9</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun find-maximum (items)
(let (max)
(dolist (item items)
Line 1,741 ⟶ 1,806:
max))
 
(find-maximum '(2 7 5)) ;=> 7</langsyntaxhighlight>
 
Built-in:
 
<langsyntaxhighlight lang="lisp">(max '(2 7 5)) ;=> 7</langsyntaxhighlight>
 
{{libheader|cl-lib}}
 
<langsyntaxhighlight lang="lisp">(cl-loop for el in '(2 7 5) maximize el) ;=> 7
(cl-reduce #'max '(2 7 5)) ;=> 7</langsyntaxhighlight>
 
{{libheader|seq.el}}
<langsyntaxhighlight lang="lisp">(seq-max '(2 7 5)) ;=> 7</langsyntaxhighlight>
 
=={{header|Erlang}}==
Builtin. Using it from the Erlang shell:
<langsyntaxhighlight lang="erlang">>lists:max([9,4,3,8,5]).
9</langsyntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MAXLIST
 
Line 1,786 ⟶ 1,851:
PRINT("Max list element is";MAX)
END PROGRAM
</syntaxhighlight>
</lang>
Note: The limit of this program is string variable lenght (255 chars). The advantage is no array use.
 
=={{header|Euler}}==
Euler allows hetrogenous lists, the <code>real</code> operator converts boolean and symbol (short character strings) to a number (leaving numeric values unchanged) and the <code>isu</code> operator tests whether its operand is <code>undefined</code> or not.
'''begin''' '''new''' greatest;
greatest &lt;- ` '''formal''' ls;
'''begin''' '''new''' L; '''new''' i; '''new''' result; '''label''' iLoop;
L &lt;- ls;
result &lt;- '''undefined''';
i &lt;- 0;
iLoop: '''if''' [ i &lt;- i + 1 ] &lt;= '''length''' L '''then''' '''begin'''
'''if''' '''isu''' result '''or''' '''real''' L[ i ] &gt; '''real''' result
'''then''' result &lt;- L[ i ] '''else''' 0;
'''goto''' iLoop
'''end''' '''else''' 0;
result
'''end'''
&apos;;
'''out''' greatest( ( '''false''', 99.0, -271, "b", 3, 4 ) )
'''end''' $
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="text">
>v=random(1,100);
>max(v)
0.997492478596
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
===Applying a function to each element of an array===
<langsyntaxhighlight Euphorialang="euphoria">function aeval( sequence sArr, integer id )
for i = 1 to length( sArr ) do
sArr[ i ] = call_func( id, { sArr[ i ] } )
Line 1,823 ⟶ 1,907:
biggun = "ant"
a = aeval( s, routine_id("biggest") )
printf( 1, "%s\n", {biggun} )</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,831 ⟶ 1,915:
 
===More trivial example===
<langsyntaxhighlight lang="euphoria">function get_biggest(sequence s)
object biggun
biggun = s[1]
Line 1,846 ⟶ 1,930:
 
constant animals = {"ant", "antelope", "dog", "cat", "cow", "wolf", "wolverine", "aardvark"}
printf(1,"%s\n",{get_biggest(animals)})</langsyntaxhighlight>
 
{{Out}}
Line 1,857 ⟶ 1,941:
Use the function MAX
 
<syntaxhighlight lang="excel">
<lang Excel>
=MAX(3;2;1;4;5;23;1;2)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,869 ⟶ 1,953:
I generate a list of 10 random numbers at runtime then use F#'s built in function to find the maximum value of the list.
 
<langsyntaxhighlight lang="fsharp">
let N = System.Random()
let G = List.init 10 (fun _->N.Next())
List.iter (printf "%d ") G
printfn "\nMax value of list is %d" (List.max G)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,883 ⟶ 1,967:
=={{header|Factor}}==
The following word is in factor's standard library.
<langsyntaxhighlight lang="factor">: supremum ( seq -- elt ) [ ] [ max ] map-reduce ;</langsyntaxhighlight>
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy">[1,-2,2,4,6,-4,-1,5] max println # => 6</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 1,892 ⟶ 1,976:
Has a built-in method to get maximum from a list.
 
<langsyntaxhighlight lang="fantom">
class Greatest
{
Line 1,902 ⟶ 1,986:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="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 ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,917 ⟶ 2,001:
The intrinsic function <tt>maxval</tt> returns the maximum value of the elements in an integer or real array:
 
<langsyntaxhighlight lang="fortran">program test_maxval
integer,dimension(5),parameter :: x = [10,100,7,1,2]
Line 1,925 ⟶ 2,009:
write(*,'(F5.1)') maxval(y)
 
end program test_maxval</langsyntaxhighlight>
 
{{Out}}
Line 1,935 ⟶ 2,019:
The intrinsic function <tt>max</tt> accepts any number of arguments.
The type of these arguments can be integer, real, character, string of characters or arrays of these.
<langsyntaxhighlight lang="fortran">program test_max
 
implicit none
Line 1,956 ⟶ 2,040:
& max (['abc', 'hig', 'fde'], ['ghi', 'efd', 'cab'], ['def', 'bca', 'igh'])
 
end program test_max</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,970 ⟶ 2,054:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function MaxElement(a() As Double) As Double
Line 1,994 ⟶ 2,078:
Print "Press any key to quit"
Sleep
</syntaxhighlight>
</lang>
 
Example of use :
Line 2,009 ⟶ 2,093:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
println[max[[1,2,3,5,10,20]]]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
Using the pre-defined function <code>max</code>:
<langsyntaxhighlight lang="funl">println( max([1,2,3,-1,0]) )</langsyntaxhighlight>
{{out}}
<pre>
Line 2,022 ⟶ 2,106:
 
It can be implemented as:
<langsyntaxhighlight lang="funl">def
maximum( xs ) =
def
Line 2,033 ⟶ 2,117:
foldl1( _, [] ) = error( "foldl1: empty list" )
 
foldl1( max, xs )</langsyntaxhighlight>
 
 
=={{header|Futhark}}==
This parallel formulation exploits the fact that negative infinity constitutes a neutral element for the maximum operator.
<syntaxhighlight lang="futhark">
let main (xs: []f64) = reduce f64.max (-f64.inf) xs
</syntaxhighlight>
 
<lang futhark>let main (xs: []f64) = reduce f64.max (-f64.inf) xs</lang>
 
 
This parallel formulation exploits the fact that negative infinity constitutes a neutral element for the maximum operator.
=={{header|FutureBasic}}==
The function fn GreatestElementInList() will sort and return the greatest element of any list that supports the @"compare:" operator.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn GreatestElementInList( list as CFArrayRef ) as CFTypeRef
CfArrayRef array = fn ArraySortedArrayUsingSelector( list, @"compare:" )
CFTypeRef result = fn ArrayLastObject( array )
end fn = result
 
CFArrayRef array
 
array = @[@1, @-2, @10, @5.0, @10.5]
NSLog( @"%@", fn GreatestElementInList( array ) )
 
// Greatest element will be letter with highest ASCII value
array = @[@"A", @"b", @"C", @"d", @"E"]
NSLog( @"%@", fn GreatestElementInList( array ) )
 
array = @[@"ant", @"antelope", @"dog", @"cat", @"cow", @"wolf", @"wolverine", @"aardvark"]
NSLog( @"%@", fn GreatestElementInList( array ) )
 
array = @[@"abc", @"123", @"zyx", @"def"]
NSLog( @"%@", fn GreatestElementInList( array ) )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre style="font-size: 13px">
10.5
d
wolverine
zyx
</pre>
 
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Greatest_element_of_a_list}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
 
Fōrmulæ provides a built-in expression "Max" that reduces to the maximum element of a given list:
 
'''Case 1. With numbers'''
 
[[File:Fōrmulæ - Greatest element of a list 01.png]]
 
[[File:Fōrmulæ - Greatest element of a list 02.png]]
 
'''Case 2. With strings'''
 
[[File:Fōrmulæ - Greatest element of a list 03.png]]
 
[[File:Fōrmulæ - Greatest element of a list 04.png]]
 
'''Case 3. With time expressions'''
 
[[File:Fōrmulæ - Greatest element of a list 05.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Greatest element of a list 06.png]]
In '''[https://formulae.org/?example=Greatest_element_of_a_list this]''' page you can see the program(s) related to this task and their results.
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="gwbasic">10 INPUT "How many items? ", N%
20 DIM ARR(N%)
30 FOR I% = 0 TO N%-1
Line 2,061 ⟶ 2,202:
100 NEXT I%
110 PRINT "The maximum value was ";CHAMP;" at index ";INDEX;"."
120 END</langsyntaxhighlight>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
 
L := List([1 .. 100], n -> Random(1, 10));
 
MaximumList(L);
# 10</langsyntaxhighlight>
 
=={{header|Go}}==
;Library
::<langsyntaxhighlight lang="go">package main
 
import (
Line 2,084 ⟶ 2,225:
fmt.Println(floats.Max([]float64{63, 70, 37, 34, 83, 27, 19, 97, 9, 17})) // prt 97
fmt.Println(floats.Min([]float64{63, 70, 37, 34, 83, 27, 19, 97, 9, 17})) // prt 9
}</langsyntaxhighlight>
::<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,109 ⟶ 2,250:
fmt.Println("The biggest number is ", biggest) // prt 97
fmt.Println("The smallest number is ", smallest) // prt 9
}</langsyntaxhighlight>
;List
The task title says list. This solution uses a Go slice as a list.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,149 ⟶ 2,290:
fmt.Println("empty list. no maximum.")
}
}</langsyntaxhighlight>
;Set
The task description says set. This solution uses a Go map as a set.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,215 ⟶ 2,356:
fmt.Println("no largest, empty set")
}
}</langsyntaxhighlight>
 
=={{header|Golfscript}}==
<langsyntaxhighlight lang="golfscript">{$-1=}:max;
[1 4 8 42 6 3]max # Example usage</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">println ([2,4,0,3,1,2,-12].max())</langsyntaxhighlight>
 
{{Out}}
Line 2,229 ⟶ 2,370:
=={{header|Haskell}}==
The built-in Haskell function <tt>maximum</tt> returns a maximum based on default comparison between members of an ordered type.
<langsyntaxhighlight lang="haskell">my_max = maximum</langsyntaxhighlight>
It can alternately be defined as a "fold" on the built-in two-argument <tt>max</tt> function.
<langsyntaxhighlight lang="haskell">my_max = foldl1 max</langsyntaxhighlight>
 
More generally, '''maximum''' is a special case of '''maximumBy''', which allows us to define or supply our own comparison function, and define the particular type of maximum that we need:
<langsyntaxhighlight lang="haskell">import Data.List (maximumBy)
import Data.Ord (comparing)
 
Line 2,241 ⟶ 2,382:
 
main :: IO ()
main = print $ maximumBy (comparing length) wds</langsyntaxhighlight>
 
As a fold, maximumBy could be defined along the lines of:
 
<langsyntaxhighlight lang="haskell">maximumBy
:: Foldable t
=> (a -> a -> Ordering) -> t a -> a
Line 2,253 ⟶ 2,394:
GT -> x
_ -> y
in foldr1 max_</langsyntaxhighlight>
 
=={{header|hexiscript}}==
<langsyntaxhighlight lang="hexiscript">fun greatest a
let l len a
let max a[0]
Line 2,265 ⟶ 2,406:
endfor
return max
endfun</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">
max_value = MAX( -123, 234.56, 345.678, -456E3, -455) ! built-in function MAX(...)
 
Line 2,291 ⟶ 2,432:
! 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
</syntaxhighlight>
</lang>
 
=={{header|Hoon}}==
<langsyntaxhighlight Hoonlang="hoon">:- %say
|= [^ [a=(list ,@) ~] ~]
:- %noun
(snag 0 (sort a gte))</langsyntaxhighlight>
Usage: Add to a file gen/max.hoon
<pre>
Line 2,305 ⟶ 2,446:
 
=={{header|i}}==
<langsyntaxhighlight lang="i">concept largest(l) {
large = l[0]
for element in l
Line 2,317 ⟶ 2,458:
software {
print(largest([23, 1313, 21, 35757, 4, 434, 232, 2, 2342]))
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">procedure main()
local l
l := [7,8,6,9,4,5,2,3,1]
Line 2,331 ⟶ 2,472:
every max <:= !l
return max
end</langsyntaxhighlight>
 
=={{headerHeader|IS-BASICInsitux}}==
 
<lang IS-BASIC>1000 DEF FINDMAX(REF ARR)
<code>max</code> is a built-in operation.
1010 LET MX=ARR(LBOUND(ARR))
 
1020 FOR I=LBOUND(ARR)+1 TO UBOUND(ARR)
<syntaxhighlight lang="insitux">
1030 LET MX=MAX(MX,ARR(I))
1040(max 1 2 NEXT3 4)
;or
1050 LET FINDMAX=MX
(... max [1 2 3 4])
1060 END DEF</lang>
</syntaxhighlight>
 
{{out}}
 
<pre>
4
</pre>
 
=={{header|J}}==
'''Solution''':<syntaxhighlight lang ="j"> >./</langsyntaxhighlight>
'''Example''':<langsyntaxhighlight Jlang="j"> >./ 1 2 3 2 1
3
>./'' NB. Maximum value of an empty list = identity element (or neutral) of max = -∞
__</langsyntaxhighlight>
 
(J's lists know how long they are.)
 
=={{header|Janet}}==
<langsyntaxhighlight lang="janet">
(def elems @[3 1 3 2])
 
Line 2,358 ⟶ 2,508:
# Unpack list as arguments to max function.
(max ;elems)
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
int max(int[] values) {
int max = values[0];
for (int value : values)
if (max < value) max = value;
return max;
}
</syntaxhighlight>
<br />
The first function works with arrays of floats. Replace with arrays of double, int, or other primitive data type.
<langsyntaxhighlight lang="java">public static float max(float[] values) throws NoSuchElementException {
if (values.length == 0)
throw new NoSuchElementException();
Line 2,371 ⟶ 2,530:
}
return themax;
}</langsyntaxhighlight>
 
Optionally, if it is OK to rearrange the contents of the original array:
<langsyntaxhighlight 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];
}</langsyntaxhighlight>
 
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 <tt>Collections.max()</tt> that already does this. For arrays, we can just use the <tt>Arrays.asList()</tt> wrapper to wrap it into a list and then use the function for lists.
<langsyntaxhighlight lang="java">import java.util.List;
import java.util.Collections;
import java.util.Arrays;
Line 2,392 ⟶ 2,551:
public static <T extends Comparable<? super T>> T max(T[] values) {
return Collections.max(Arrays.asList(values));
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES3-5===
<langsyntaxhighlight lang="javascript">Math.max.apply(null, [ 0, 1, 2, 5, 4 ]); // 5</langsyntaxhighlight>
 
===ES 5 maxima beyond simple numeric data types===
Line 2,402 ⟶ 2,561:
Math.max() serves well with simple numeric types, but for less restricted use we can write a generic '''maximumBy''' function which returns the maximum value from an array containing a series of any consistent data type, and which takes a type-specific comparison function as an argument.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// (a -> a -> Ordering) -> [a] -> a
Line 2,494 ⟶ 2,653:
]
 
})();</langsyntaxhighlight>
 
 
{{Out}}
 
<syntaxhighlight lang="javascript">[
<lang JavaScript>[
"alpha",
"zeta",
Line 2,519 ⟶ 2,678:
"population": 13.3
}
]</langsyntaxhighlight>
 
===ES6===
For, numbers, a method of the standard Math object:
<langsyntaxhighlight lang="javascript">Math.max(...[ 0, 1, 2, 5, 4 ]); // 5</langsyntaxhighlight>
 
and for orderings defined over other datatypes:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
// ----------- GREATEST ELEMENT OF A LIST ------------
 
// maximumByMay :: (a -> a -> Ordering) ->
Line 2,533 ⟶ 2,694:
const maximumByMay = f =>
// Nothing, if the list is empty,
// or just the maximum value when compared in
// in terms of f.
xs => Boolean(xs.length) ? (
Just(xs.slice(1).reduce(
Line 2,617 ⟶ 2,778:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[
Line 2,626 ⟶ 2,787:
}
]</pre>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE maximum == unswons [max] fold.</syntaxhighlight>
 
=={{header|jq}}==
jq defines a total ordering of all JSON entities, and the <tt>max</tt> filter can accordingly be used on any JSON array:
<langsyntaxhighlight lang="jq">[1, 3, 1.0] | max # => 3
 
[ {"a": 1}, {"a":3}, {"a":1.0}] | max # => {"a": 3}</langsyntaxhighlight>
Warning: both "[null]|max" and "[]|max" yield null.
 
Given a stream, s, of JSON values, the following filter will emit null if the stream is empty, or the maximum value otherwise:
<langsyntaxhighlight lang="jq">reduce s as $x (null; if $x > . then $x else . end)</langsyntaxhighlight>
 
=={{header|Julia}}==
Using the built-in <code>maximum</code> function:
<langsyntaxhighlight lang="julia">julia> maximum([1,3,3,7])
7
 
Line 2,652 ⟶ 2,816:
at In[138]:1
in maximum at abstractarray.jl:1591
</syntaxhighlight>
</lang>
(Note that it throws an exception on an empty array.)
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> |/ 6 1 7 4
7</langsyntaxhighlight>
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
( "1" "1234" "62" "234" "12" "34" "6" )
Line 2,672 ⟶ 2,836:
"Numeric order: " print lmax ?
 
" " input</langsyntaxhighlight>
 
=={{header|Klong}}==
<langsyntaxhighlight lang="k">list::[ 1.0 2.3 1.1 5.0 3 2.8 2.01 3.14159 77 ]
|/list
|/ [ 1.0 2.3 1.1 5.0 3 2.8 2.01 3.14159 66 ]
|/ 1.0,2.3,1.1,5.0,3,2.8,2.01,3.14159,55</langsyntaxhighlight>
{{out}}
<pre>77
Line 2,686 ⟶ 2,850:
 
=={{header|Kotlin}}==
Kotlin already has a 'max'() function in its standard library sothat weapplies useto collection of Iterable that:
<lang scala>// version 1.0.5-2
fun main(args: Array<String>) {
print("Number of values to be input = ")
val n = readLine()!!.toInt()
val array = DoubleArray(n)
for (i in 0 until n) {
print("Value ${i + 1} = ")
array[i] = readLine()!!.toDouble()
}
println("\nThe greatest element is ${array.max()}")
}</lang>
Example of use:
{{out}}
<pre>
Number of values to be input = 4
Value 1 = 70.5
Value 2 = 23.67
Value 3 = 150.2
Value 4 = 145
 
<syntaxhighlight lang="kotlin">
The greatest element is 150.2
fun main() {
</pre>
listOf(1.0, 3.5, -1.1).max().also { println(it) } // 3.5
listOf(1, 3, -1).max().also { println(it) } // 3
setOf(1, 3, -1).max().also { println(it) } // 3
}
</syntaxhighlight>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
1) using the builtin primitive
 
Line 2,734 ⟶ 2,884:
{my-max {A.new 556 1 7344 4 7 52 22 55 88 122 55 99 1222 578}}
-> 7344
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="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)</langsyntaxhighlight>
 
{{out}}
<pre>7344</pre>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
values is number list
n is number
 
procedure:
sub max
parameters:
x is number list
result is number
local data:
i is number
procedure:
store x:0 in result
for each i in values do
if i is greater than result then
store i in result
end if
repeat
end sub
create statement "get maximum of list $ in $" executing max
 
# Now let's use the sub-procedure.
push 1 to values
push 11 to values
push 5 to values
push 33 to values
push 99 to values
push 13 to values
push 37 to values
push 50 to values
 
get maximum of list values in n
display "The maximum is " n lf
</syntaxhighlight>
{{out}}
<pre>
The maximum is 99
</pre>
 
=={{header|LFE}}==
Builtin. Using it from the LFE shell:
<langsyntaxhighlight lang="lisp">>(: lists max '[9 4 3 8 5])
9</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">aList$= "1 15 -5 6 39 1.5 14"
 
maxVal = val(word$(aList$, 1))
Line 2,764 ⟶ 2,954:
wend
 
print "maxVal = ";maxVal</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">l = [1,7,5]
put max(l)
-- 7</langsyntaxhighlight>
 
=={{header|LiveCode}}==
 
Max is built-in<langsyntaxhighlight lang="livecode">put max(2,3,6,7,4,1)</langsyntaxhighlight>
Result: 7
 
To be fair to the exercise, an alternative implementation could be<langsyntaxhighlight liveCodelang="livecode">function max2 lst
local maxNum
put item 1 of lst into maxNum
Line 2,788 ⟶ 2,978:
on mouseUp
answer max2("1,2,5,6,7,4,3,2")
end mouseUp</langsyntaxhighlight>
 
=={{header|Logo}}==
Line 2,796 ⟶ 2,986:
to use APPLY instead of REDUCE. The latter is good for associative
procedures that have been written to accept exactly two inputs:
<langsyntaxhighlight lang="logo">to max :a :b
output ifelse :a > :b [:a] [:b]
end
 
print reduce "max [...]</langsyntaxhighlight>
 
Alternatively, REDUCE can be used to write MAX as a procedure
that accepts any number of inputs, as SUM does:
<langsyntaxhighlight lang="logo">to max [:inputs] 2
if emptyp :inputs ~
[(throw "error [not enough inputs to max])]
output reduce [ifelse ?1 > ?2 [?1] [?2]] :inputs
end</langsyntaxhighlight> =={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">to bigger :a :b
output ifelse [greater? :a :b] [:a] [:b]
end
Line 2,816 ⟶ 3,006:
to max :lst
output reduce "bigger :lst
end</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">
max([X| Xs], Max) :-
max(Xs, X, Max).
Line 2,828 ⟶ 3,018:
max(Xs, X, Max)
; max(Xs, Aux, Max)
).</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">-- Table to store values
local values = {}
-- Read in the first number from stdin
Line 2,844 ⟶ 3,034:
-- Print the max
print(math.max(unpack(values)))
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module TestThis {
Print "Search a tuple type list (is an array also)"
Line 2,924 ⟶ 3,114:
}
TestThis
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
This is a built-in, polymorphic procedure in Maple.
<langsyntaxhighlight Maplelang="maple">> max( { 1, 2, Pi, exp(1) } ); # set
Pi
 
Line 2,938 ⟶ 3,128:
 
> max( Array( [ 1, 2, Pi, exp(1) ] ) ); # Array
Pi</langsyntaxhighlight>
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.
<langsyntaxhighlight Maplelang="maple">> A := Array([1,2,4/5,3,11]): rtable_scanblock( A, [rtable_dims(A)], Maximum );
11</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Input:
<langsyntaxhighlight Mathematicalang="mathematica">Max[1, 3, 3, 7]
Max[Pi,E+2/5,17 Cos[6]/5,Sqrt[91/10]]
Max[1,6,Infinity]
Max[]</langsyntaxhighlight>
{{Out}}
<pre> 7
Line 2,955 ⟶ 3,145:
-Infinity</pre>
Note that Max returns minus infinity if supplied with no arguments; as it should:
<langsyntaxhighlight Mathematicalang="mathematica">Max[Max[],Max[a,b,c]]
Max[Max[a],Max[b,c]]
Max[Max[a,b],Max[c]]
Max[Max[a,b,c],Max[]]</langsyntaxhighlight>
should all give the same results, therefore max[] should give -Infinity. If it WOULD give 0 strange things can happen:
<langsyntaxhighlight Mathematicalang="mathematica">Max[Max[], Max[-4, -3]]</langsyntaxhighlight>
WOULD give 0 instead of -3
 
=={{header|MATLAB}}==
<langsyntaxhighlight Matlablang="matlab">function [maxValue] = findmax(setOfValues)
maxValue = max(setOfValues);</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">u : makelist(random(1000), 50)$
 
/* Three solutions */
Line 2,975 ⟶ 3,165:
apply(max, u);
 
lmax(u);</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight MAXScriptlang="maxscript">fn MaxValue AnArray =
(
if AnArray.count != 0 then
Line 2,989 ⟶ 3,179:
)
else undefined
)</langsyntaxhighlight>
 
=={{header|Metafont}}==
Line 2,995 ⟶ 3,185:
The <code>max</code> 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).
 
<langsyntaxhighlight lang="metafont">show max(4,5,20,1);
show max((12,3), (10,10), (25,5));
show max("hello", "world", "Hello World");</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.1937.30}}
<syntaxhighlight lang="min">(() ('> 'pop 'nip if) map-reduce) ^max
<lang min>(
 
'bool ;does the list have any elements?
(5 3 2 7 4) max puts!</syntaxhighlight>
(-inf ('> 'pop 'nip if) reduce) ;do if so
({"empty seq" :error "Cannot find the maximum element of an empty sequence" :message} raise) ;do if not
if
) :seq-max</lang>
 
=={{header|MiniScript}}==
There is a list.max function in the listUtil module, but if you're working in an environment without this module or just want to write it yourself, you might do it as follows.
<langsyntaxhighlight MiniScriptlang="miniscript">list.max = function()
if not self then return null
result = self[0]
Line 3,019 ⟶ 3,206:
end function
 
print [47, 11, 42, 102, 13].max</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П0 С/П x=0 07 ИП0 x<0 00 max БП 00</langsyntaxhighlight>
 
or
 
<syntaxhighlight lang="text">П0 ИП0 С/П - x<0 01 Вx П0 БП 01</langsyntaxhighlight>
 
=={{header|Modula-3}}==
Line 3,032 ⟶ 3,219:
 
We provide a generic Maximum implementation:
<langsyntaxhighlight lang="modula3">GENERIC INTERFACE Maximum(Elem);
 
EXCEPTION Empty;
Line 3,038 ⟶ 3,225:
PROCEDURE Max(READONLY a: ARRAY OF Elem.T): Elem.T RAISES {Empty};
 
END Maximum.</langsyntaxhighlight>
 
<langsyntaxhighlight lang="modula3">GENERIC MODULE Maximum(Elem);
 
PROCEDURE Max(READONLY arr: ARRAY OF Elem.T): Elem.T RAISES {Empty} =
Line 3,057 ⟶ 3,244:
 
BEGIN
END Maximum.</langsyntaxhighlight>
 
<code>Elem</code> 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:
<langsyntaxhighlight lang="modula3">INTERFACE RealMax = Maximum(Real) END RealMax.</langsyntaxhighlight>
<langsyntaxhighlight lang="modula3">MODULE RealMax = Maximum(Real) END RealMax.</langsyntaxhighlight>
 
Now we can import <code>RealMax</code> into our source and use the <code>Max</code> function:
<langsyntaxhighlight lang="modula3">MODULE Main;
 
IMPORT RealMax, IO, Fmt;
Line 3,074 ⟶ 3,261:
BEGIN
IO.Put(Fmt.Real(RealMax.Max(realarr)) & "\n");
END Main.</langsyntaxhighlight>
 
=={{header|MontiLang}}==
MontiLang has a builtin statement <code>MAX</code> which finds the maximum of the top two items on the stack. By looping through an array and pushing to the stack, the largest item in an array can be found.
<langsyntaxhighlight MontiLanglang="montilang">2 5 3 12 9 9 56 2 ARR
 
LEN VAR l .
Line 3,089 ⟶ 3,276:
FOR st
MAX
ENDFOR PRINT</langsyntaxhighlight>
 
Another way to do it.
 
<langsyntaxhighlight MontiLanglang="montilang">2 5 3 12 9 9 56 2 ARR
print
LEN VAR l .
Line 3,105 ⟶ 3,292:
|Greatest number in the list: | out . print
|Press ENTER to exit | input
clear</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">
<lang MUMPS>
MV(A,U)
;A is a list of values separated by the string U
Line 3,114 ⟶ 3,301:
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
</syntaxhighlight>
</lang>
Usage:
<pre>
Line 3,126 ⟶ 3,313:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">def max(list)
if len(list) = 0
return null
Line 3,138 ⟶ 3,325:
end
return largest
end</langsyntaxhighlight>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
greatest element from a list (Neko Array)
Tectonics:
Line 3,164 ⟶ 3,351:
 
$print(greatest($array(5, 1, 3, 5)), "\n");
$print(greatest($array("abc", "123", "zyx", "def")), "\n");</langsyntaxhighlight>
 
{{out}}
Line 3,173 ⟶ 3,360:
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using Nemerle.Collections;
using System.Linq;
Line 3,200 ⟶ 3,387:
WriteLine($"letters.Max() = $(letters.Max())")
}
}</langsyntaxhighlight>
 
{{Out}}
Line 3,209 ⟶ 3,396:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols binary
Line 3,241 ⟶ 3,428:
end n_
return dmax
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,249 ⟶ 3,436:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(max 1 2 3 5 2 3 4)</langsyntaxhighlight>
 
<langsyntaxhighlight NEWLISPlang="newlisp">(apply max '(1 2 3 5 2 3 4)) ; apply to list
; Added by Nehal-Singhal 2018-05-29</langsyntaxhighlight>
 
=={{header|Nial}}==
The behavior of multi-dimensional arrays is like J
 
<langsyntaxhighlight lang="nial">max 1 2 3 4
=4</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">echo max([2,3,4,5,6,1])</langsyntaxhighlight>
 
{{out}}<pre>6</pre>
Line 3,267 ⟶ 3,454:
=={{header|Oberon-2}}==
{{Works with|oo2c Version 2}}
<langsyntaxhighlight lang="oberon2">
MODULE GreatestElement1;
IMPORT
Line 3,306 ⟶ 3,493:
Out.String("Max: ");Out.LongInt(max.value,4);Out.Ln
END GreatestElement1.
</syntaxhighlight>
</lang>
 
Simple version
<langsyntaxhighlight lang="oberon2">
MODULE GreatestElement2;
IMPORT
Line 3,336 ⟶ 3,523:
Out.String("Max: ");Out.LongInt(Max(a),4);Out.Ln
END GreatestElement2.
</syntaxhighlight>
</lang>
{{out}}(in both programs):
<pre>
Line 3,344 ⟶ 3,531:
=={{header|Objeck}}==
The language has a "Max" method for vectors.
<langsyntaxhighlight lang="objeck">
values := IntVector->New([4, 1, 42, 5]);
values->Max()->PrintLine();
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
Line 3,367 ⟶ 3,554:
 
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface NSArray (WithMaximum)
Line 3,389 ⟶ 3,576:
return maybeMax;
}
@end</langsyntaxhighlight>
 
This example mixes integers with a double value, just to show that
everything is fine until they are NSNumber.
 
<langsyntaxhighlight lang="objc">int main()
{
@autoreleasepool {
Line 3,402 ⟶ 3,589:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let my_max = function
[] -> invalid_arg "empty list"
| x::xs -> List.fold_left max x xs</langsyntaxhighlight>
 
# my_max [4;3;5;9;2;3] ;;
Line 3,416 ⟶ 3,603:
Octave's <code>max</code> accepts a vector (and can return also the index of the maximum value in the vector)
 
<langsyntaxhighlight lang="octave">m = max( [1,2,3,20,10,9,8] ); % m = 20
[m, im] = max( [1,2,3,20,10,9,8] ); % im = 4</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">[1, 2.3, 5.6, 1, 3, 4 ] reduce(#max)</langsyntaxhighlight>
 
=={{header|Ol}}==
Basics:
<langsyntaxhighlight lang="scheme">
; builtin function
(max 1 2 3 4 5) ; 5
Line 3,441 ⟶ 3,628:
(if (less? a b) b a))
(car x) x)) ; 5
</syntaxhighlight>
</lang>
 
=={{header|ooRexx}}==
===version===
<syntaxhighlight lang="oorexx">
<lang ooRexx>
-- routine that will work with any ordered collection or sets and bags containing numbers.
::routine listMax
Line 3,461 ⟶ 3,648:
 
return largest
</syntaxhighlight>
</lang>
 
===version 2 works with any strings===
<syntaxhighlight lang="text">/* REXX ***************************************************************
* 30.07.2013 Walter Pachl as for REXX
**********************************************************************/
Line 3,481 ⟶ 3,668:
largest = item
end
return largest</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="text">
'Works on any list with element types which support '>' comparisons
 
Line 3,507 ⟶ 3,694:
double m=max(d,5)
print "greatest element of d(): " m '5.5
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="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]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang ="parigp">vecmax(v)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 3,524 ⟶ 3,711:
{{works with | Free Pascal}}
or try this, for it shows the according position
<langsyntaxhighlight lang="pascal">program GElemLIst;
{$IFNDEF FPC}
{$Apptype Console}
Line 3,624 ⟶ 3,811:
Ergflt := FindMaxflt(fltArr);
writeln('FindMaxFlt ',Ergflt.mpMax:0:4,' @ ',Ergflt.mpPos);
end.</langsyntaxhighlight>
Out, because of the searchdirection Position of FindMaxFlt is below FindMaxInt
 
Line 3,632 ⟶ 3,819:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub max {
my $max = shift;
for (@_) { $max = $_ if $_ > $max }
return $max;
}</langsyntaxhighlight>
 
It is already implemented in the module <tt>List::Util</tt>'s <tt>max()</tt> function:
<langsyntaxhighlight lang="perl">use List::Util qw(max);
 
max(@values);</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1234</span><span style="color: #0000FF;">,</span><span style="color: #000000;">62</span><span style="color: #0000FF;">,</span><span style="color: #000000;">234</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span><span style="color: #000000;">34</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"ant"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"antelope"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"dog"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"cat"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"cow"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"wolf"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"wolverine"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"aardvark"</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,656 ⟶ 3,843:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">"1" "1234" "62" "234" "12" "34" "6" stklen tolist
dup "Alphabetic order: " print max print nl
 
Line 3,663 ⟶ 3,850:
i get tonum i set
endfor
"Numeric order: " print max print</langsyntaxhighlight>
 
With syntactic sugar
 
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
( "1" "1234" "62" "234" "12" "34" "6" )
Line 3,680 ⟶ 3,867:
 
dup "Numeric order: " print max print
</syntaxhighlight>
</lang>
 
=={{header|PHP}}==
The built-in PHP function <tt>max()</tt> already does this.
<syntaxhighlight lang ="php">max($values)</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="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</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
maximum = A(lbound(A,1));
do i = lbound(A,1)+1 to hbound(A,1);
if maximum < A(i) then maximum = A(i);
end;
</syntaxhighlight>
</lang>
 
=={{header|PostScript}}==
Line 3,707 ⟶ 3,894:
 
{{works with|Ghostscript}}
<langsyntaxhighlight lang="postscript">/findmax {
dup 0 get exch % put the first element underneath the array
{max} forall % replace it by the respective larger value if necessary
} def</langsyntaxhighlight>
 
If not using Ghostscript this gets a bit longer:
 
<langsyntaxhighlight lang="postscript">/findmax {
dup 0 get exch % put the first element underneath the array
{
Line 3,723 ⟶ 3,910:
pop % remove it
} forall
} def</langsyntaxhighlight>
 
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
[1 2 3 4 5 4 3 2 1] uncons exch {max} fold
</syntaxhighlight>
</lang>
 
=={{header|PowerBASIC}}==
 
<langsyntaxhighlight lang="powerbasic">FUNCTION PBMAIN()
DIM x AS LONG, y AS LONG, z AS LONG
RANDOMIZE TIMER
Line 3,742 ⟶ 3,929:
 
? STR$(z) & " was the highest value"
END FUNCTION</langsyntaxhighlight>
 
{{Out}}
Line 3,751 ⟶ 3,938:
=={{header|PowerShell}}==
The <code>Measure-Object</code> cmdlet in PowerShell already has this capability:
<langsyntaxhighlight lang="powershell">function Get-Maximum ($a) {
return ($a | Measure-Object -Maximum).Maximum
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
SWI-Prolog already knows max_list.
<langsyntaxhighlight Prologlang="prolog"> ?- max_list([1, 2, 10, 3, 0, 7, 9, 5], M).
M = 10.</langsyntaxhighlight>
 
can be implemented like this:
 
<langsyntaxhighlight Prologlang="prolog">max_list(L, V) :-
select(V, L, R), \+((member(X, R), X > V)).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.f Max (Array a.f(1))
Protected last, i, ret.f
 
Line 3,779 ⟶ 3,966:
ProcedureReturn ret
EndProcedure</langsyntaxhighlight>
===PureBasic: another solution===
<langsyntaxhighlight lang="purebasic">Procedure.f maxelement(List tl.f())
ForEach tl() : mx.f=mx*Bool(mx>=tl())+tl()*Bool(mx<tl()) : Next
ProcedureReturn mx
Line 3,788 ⟶ 3,975:
NewList testlist.f() : OpenConsole()
For i=0 To 99 : AddElement(testlist()) : testlist()=Sqr(Random(1000)) : Next
Print("Greatest element = "+StrF(maxelement(testlist()),8)) : Input()</langsyntaxhighlight>
{{out}}
<pre>Greatest element = 31.59113884</pre>
 
=={{header|Python}}==
===Numeric values===
The built-in Python function <tt>max()</tt> already does this.
<syntaxhighlight lang ="python">max(values)</langsyntaxhighlight>
 
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 3,801 ⟶ 3,989:
 
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
<langsyntaxhighlight lang="python">>>> floatstrings = ['1\n', ' 2.3\n', '4.5e-1\n', '0.01e4\n', '-1.2']
>>> max(floatstrings, key = float)
'0.01e4\n'
>>></langsyntaxhighlight>
Normally we would want the converted form as the maximum and we could just as easily write:
<langsyntaxhighlight lang="python">>>> max(float(x) for x in floatstrings)
100.0
>>></langsyntaxhighlight>
Or you can write your own functional version, of the maximum function, using reduce and lambda
<langsyntaxhighlight lang="python">>>> mylist = [47, 11, 42, 102, 13]
>>> reduce(lambda a,b: a if (a > b) else b, mylist)
102</langsyntaxhighlight>
 
And if you are being lazy but still want to meet this task's requirements :
 
<syntaxhighlight lang="python">
max(list(map(int,input("").split(","))))
</syntaxhighlight>
 
===Non-numeric values===
 
<syntaxhighlight lang="python">'''Non-numeric maxima'''
 
print(
f'max a-z: "{max(["epsilon", "zeta", "eta", "theta"])}"'
)
print(
f'max length: "{max(["epsilon", "zeta", "eta", "theta"], key=len)}"'
)
print(
'max property k by a-z: ' + str(max([
{"k": "epsilon", "v": 2},
{"k": "zeta", "v": 4},
{"k": "eta", "v": 32},
{"k": "theta", "v": 16}], key=lambda x: x["k"]))
)
print(
'max property k by length: ' + str(max([
{"k": "epsilon", "v": 2},
{"k": "zeta", "v": 4},
{"k": "eta", "v": 32},
{"k": "theta", "v": 16}], key=lambda x: len(x["k"])))
)
print(
'max property v: ' + str(max([
{"k": "epsilon", "v": 2},
{"k": "zeta", "v": 4},
{"k": "eta", "v": 32},
{"k": "theta", "v": 16}], key=lambda x: x["v"]))
)</syntaxhighlight>
{{Out}}
<pre>max a-z: "zeta"
max length: "epsilon"
max property k by a-z: {'k': 'zeta', 'v': 4}
max property k by length: {'k': 'epsilon', 'v': 2}
max property v: {'k': 'eta', 'v': 32}</pre>
 
=={{header|Q}}==
<langsyntaxhighlight Qlang="q">q)l:2 9 3 8 4 7
q)max l
9</langsyntaxhighlight>
 
=={{header|Quackery}}==
<langsyntaxhighlight Quackerylang="quackery">[ behead swap witheach max ] is [max] ( [ --> n )</langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">v <- c(1, 2, 100, 50, 0)
print(max(v)) # 100</langsyntaxhighlight>
 
=={{header|Racket}}==
The "max" function it built in and takes an arbitrary amount of arguments.
<langsyntaxhighlight lang="racket">(max 12 9 8 17 1)</langsyntaxhighlight>
{{Out}}
<pre>17</pre>
 
To use with a list, there is <tt>apply</tt>:
<langsyntaxhighlight lang="racket">(apply max '(12 9 8 17 1))</langsyntaxhighlight>
 
However, if you want to write the function yourself:
<langsyntaxhighlight lang="racket">
(define (my-max l)
(define (max-h l greatest)
Line 3,843 ⟶ 4,075:
[else (max-h (rest l) greatest)]))
(if (empty? l) empty (max-h l (first l))))
</syntaxhighlight>
</lang>
 
or with a "for" loop:
<langsyntaxhighlight lang="racket">
(define (my-max l)
(for/fold ([max #f]) ([x l])
(if (and max (> max x)) max x)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
The built-in function works with any type that defines ordering.
<syntaxhighlight lang="raku" perl6line>say max 10, 4, 5, -2, 11;
say max <zero one two three four five six seven eight nine>;
 
Line 3,861 ⟶ 4,093:
my @list = flat(0..9,'A'..'H').roll((^60).pick).rotor(4,:partial)».join.words;
say @list, ': ', max @list;
</syntaxhighlight>
</lang>
{{out|Sample output}}
<pre>11
Line 3,868 ⟶ 4,100:
 
=={{header|RapidQ}}==
<langsyntaxhighlight lang="vb">functioni FindMax(...) as double
dim x as integer
Line 3,877 ⟶ 4,109:
 
Print FindMax(50, 20, 65, 20, 105)
</syntaxhighlight>
</lang>
 
=={{header|Rascal}}==
Rascal has a built-in function that gives the greatest element of a list
<langsyntaxhighlight lang="rascal">
rascal>import List;
ok
Line 3,887 ⟶ 4,119:
rascal>max([1,2,3,4]);
int: 4
</syntaxhighlight>
</lang>
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">[ 1 2 3 4 ] max "%d\n" print</langsyntaxhighlight>
{{out}} <pre>4</pre>
 
'''Randomly generated list size and elements'''
<langsyntaxhighlight Ravenlang="raven">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</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Maximum Value"
URL: http://rosettacode.org/wiki/Maximum_Value
Line 3,914 ⟶ 4,146:
 
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]</langsyntaxhighlight>
 
{{Out}}
Line 3,921 ⟶ 4,153:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
list: [1 2 3 5 4]
print last sort list
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
The numbers in the list may be any valid REXX number &nbsp; (integer, negative, floating point, etc.)
===using a list===
<langsyntaxhighlight lang="rexx">/*REXX program finds the greatest element in a list (of the first 25 reversed primes).*/
$ = reverse(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)
say 'list of numbers = ' $ /*show the original list of numbers. */
Line 3,937 ⟶ 4,169:
end /*j*/
say /*stick a fork in it, we're all done. */
say 'the biggest value in a list of ' # " numbers is: " big</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) input:}}
<pre>
Line 3,946 ⟶ 4,178:
 
===using an array===
<langsyntaxhighlight lang="rexx">/*REXX program finds the greatest element in a list (of the first 25 reversed primes).*/
@.=; @.1 = 2; @.2 = 3; @.3 = 5; @.4 = 7; @.5 =11; @.6 =31; @.7 =71
@.8 =91; @.9 =32; @.10=92; @.11=13; @.12=73; @.13=14; @.14=34
Line 3,956 ⟶ 4,188:
end /*#*/
/*stick a fork in it, we're all done. */
say 'the biggest value in an array of ' #-1 " elements is: " big</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) input:}}
<pre>
Line 3,963 ⟶ 4,195:
 
===using a list from the terminal===
<langsyntaxhighlight lang="rexx">/*REXX program finds the greatest element in a list of numbers entered at the terminal*/
say '────────────────── Please enter a list of numbers (separated by blanks or commas):'
parse pull $; #=words($) /*get a list of numbers from terminal. */
Line 3,971 ⟶ 4,203:
end /*j*/
say /*stick a fork in it, we're all done. */
say '────────────────── The biggest value in the list of ' # " elements is: " big</langsyntaxhighlight>
Programming note: &nbsp; the &nbsp; '''max''' &nbsp; BIF normalizes the number returned (eliding the leading superfluous zeroes).
 
If this is undesirable, then the &nbsp; '''do''' &nbsp; loop (shown above) can be replaced with:
<langsyntaxhighlight lang="rexx">···; do j=2 to #; _=word($,j)
if _>big then big=_
end /*j*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input from the terminal via a user prompt:}}
<pre>
Line 3,987 ⟶ 4,219:
 
===list of any strings===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* If the list contains any character strings, the following will work
* Note the use of >> (instead of >) to avoid numeric comparison
Line 4,005 ⟶ 4,237:
max=word(l,i)
End
Return max</langsyntaxhighlight>
{{out|output|text=&nbsp; when using an &nbsp; '''ASCII''' &nbsp; system:}}
<pre>
Line 4,023 ⟶ 4,255:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">aList = [1,2,4,5,10,6,7,8,9]
see max(aList)</langsyntaxhighlight>
{{out}}
<pre>
10
</pre>
 
=={{header|RPL}}==
{{works with|HP|48}}
{ 2 718 28 18 28 46 } ≪ MAX ≫ STREAM
{{out}}
<pre>
1: 718
</pre>
 
=={{header|Ruby}}==
<tt>max</tt> is a method of all Enumerables
<syntaxhighlight lang ="ruby">values.max</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">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</langsyntaxhighlight>
 
=={{header|Rust}}==
This is built in functionality for everything that can be iterated over. It returns an Option<T>, meaning Some(e) if there are elements in the iterator and None if it is empty.
<langsyntaxhighlight lang="rust">fn main() {
let nums = [1,2,39,34,20];
println!("{:?}", nums.iter().max());
println!("{}", nums.iter().max().unwrap());
}</langsyntaxhighlight>
 
{{out}}
Line 4,056 ⟶ 4,296:
=={{header|S-lang}}==
Starting w/an array, this is trivial:
<langsyntaxhighlight Slang="s-lang">variable a = [5, -2, 0, 4, 666, 7];
print(max(a));</langsyntaxhighlight>
 
output:
Line 4,063 ⟶ 4,303:
 
If a is a list instead of an array, then:
<langsyntaxhighlight Slang="s-lang">a = {5, -2, 0, 4, 666, 7};
print(max(list_to_array(a)));</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">def noSweat(list: Int*) = list.max
// Test
assert(noSweat(1, 3, 12, 7) == 12)</langsyntaxhighlight>
 
=={{header|Scheme}}==
The built-in Scheme function <tt>max</tt> takes the max of all its arguments.
<langsyntaxhighlight lang="scheme">(max 1 2 3 4)
(apply max values) ; find max of a list</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: max (in array integer: values) is func
Line 4,097 ⟶ 4,337:
begin
writeln(max([] (1, 2, 6, 4, 3)));
end func;</langsyntaxhighlight>
 
{{Out}}
Line 4,107 ⟶ 4,347:
Using ''reduceWith:'' it is very simple to find the maximum value among a collection.
 
<langsyntaxhighlight lang="self">(1 & 2 & 3 & 4 & 20 & 10 & 9 & 8) asVector reduceWith: [:a :b | a max: b] "returns 20"</langsyntaxhighlight>
 
Or, since it's "built-in", you can simply do:
 
<langsyntaxhighlight lang="self">(1 & 2 & 3 & 4 & 20 & 10 & 9 & 8) asVector max. "returns 20"</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">put the max of (1, 5, 666, -1000, 3)
put the highest value of [88,-2,6,55,103,0]</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="sensetalk">666
103</langsyntaxhighlight>
 
=={{header|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).
<syntaxhighlight lang ="ruby">values.max;</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">#(1 2 3 4 20 10 9 8) reduce: [| :a :b | a max: b]</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Using ''fold'' it is very simple to find the maximum value among a collection.
 
<langsyntaxhighlight lang="smalltalk">#(1 2 3 4 20 10 9 8) fold: [:a :b | a max: b] "returns 20"</langsyntaxhighlight>
 
Or, since it's "built-in", you can simply do:
Line 4,136 ⟶ 4,376:
{{works with|Pharo|1.4}}
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">#(1 2 3 4 20 10 9 8) max. "returns 20"</langsyntaxhighlight>
 
using #inject:into:
<langsyntaxhighlight lang="smalltalk">
| list |
list := #(1 2 3 4 20 10 9 8).
list inject: (list at: 1) into: [ :number :each |
number max: each ]
</syntaxhighlight>
</lang>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang="snobol4">while a = trim(input) :f(stop)
max = gt(a,max) a :(while)
stop output = max
end</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Comparisons are specific for each type. Here is a max function for a list of ints:
<langsyntaxhighlight lang="sml">fun max_of_ints [] = raise Empty
| max_of_ints (x::xs) = foldl Int.max x xs</langsyntaxhighlight>
 
- max_of_ints [4,3,5,9,2,3];
Line 4,164 ⟶ 4,404:
Use the '''[https://www.stata.com/help.cgi?summarize summarize]''' command to compute the maximum value of a variable:
 
<langsyntaxhighlight lang="stata">qui sum x
di r(max)</langsyntaxhighlight>
 
Mata has also several [https://www.stata.com/help.cgi?mf_minmax functions] to compute minimum or maximum of a vactor or matrix:
 
<langsyntaxhighlight lang="stata">a = 1,5,3,4,2,7,9,8
max(a)</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|2.x}}
<langsyntaxhighlight lang="swift">if let x = [4,3,5,9,2,3].maxElement() {
print(x) // prints 9
}</langsyntaxhighlight>
{{works with|Swift|1.x}}
<langsyntaxhighlight lang="swift">let x = maxElement([4,3,5,9,2,3])
println(x) // prints 9</langsyntaxhighlight>
 
=={{header|Tailspin}}==
Simplest is to use the built-in collector
<langsyntaxhighlight lang="tailspin">
[1, 5, 20, 3, 9, 7] ... -> ..=Max&{by: :(), select: :()} -> !OUT::write
// outputs 20
Line 4,192 ⟶ 4,432:
sink accumulate
<?($@Max <=[]>)
| ?($(by) <$@Max.max(1)..>)> @Max: {max: [$(by), result: $(select)}];
end accumulate
source result
$@Max.result(2) !
end result
end Max
</syntaxhighlight>
</lang>
But here is how to find the max more manually/programmatically, it is pretty easy as well
<langsyntaxhighlight lang="tailspin">
templates max
@: $(1);
Line 4,210 ⟶ 4,450:
[1, 5, 20, 3, 9, 7] -> max -> !OUT::write
// outputs 20
</syntaxhighlight>
</lang>
Can also be written as an inline templates
<langsyntaxhighlight lang="tailspin">
[1, 5, 20, 3, 9, 7] -> \(@: $(1); $(2..last)... -> # $@ ! when <$@..> do @: $;\) -> !OUT::write
// outputs 20
</syntaxhighlight>
</lang>
Or we can do just the matching in an inline templates referencing the outer state
<langsyntaxhighlight lang="tailspin">
templates max
@: $(1);
Line 4,226 ⟶ 4,466:
[1, 5, 20, 3, 9, 7] -> max -> !OUT::write
// outputs 20
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
Use the <code>{*}</code> expansion operator to substitute the list value with its constituent elements
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
set values {4 3 2 7 8 9}
::tcl::mathfunc::max {*}$values ;# ==> 9</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 4,245 ⟶ 4,485:
 
=={{header|Transd}}==
<langsyntaxhighlight lang="scheme">#lang transd
 
MainModule: {
Line 4,254 ⟶ 4,494:
(textout (max-element-idx v))
))
}</langsyntaxhighlight>{{out}}
<pre>
11 274 3
Line 4,260 ⟶ 4,500:
 
=={{header|Trith}}==
<langsyntaxhighlight lang="trith">[1 -2 3.1415 0 42 7] [max] foldl1</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
LOOP n,list="2'4'0'3'1'2'-12"
Line 4,270 ⟶ 4,510:
ENDLOOP
PRINT greatest
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,278 ⟶ 4,518:
=={{header|uBasic/4tH}}==
Since uBasic/4tH has a stack, it's only logical to use it.
<syntaxhighlight lang="text">Push 13, 0, -6, 2, 37, -10, 12 ' Push values on the stack
Print "Maximum value = " ; FUNC(_FNmax(7))
End ' We pushed seven values
Line 4,291 ⟶ 4,531:
If c@ > d@ THEN d@ = c@ ' Change maximum if required
Next
Return (d@) ' Return the maximum</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 4,297 ⟶ 4,537:
{{works with|pdksh}}
 
<langsyntaxhighlight lang="bash">max() {
local m=$1
shift
Line 4,308 ⟶ 4,548:
}
 
max 10 9 11 57 1 12</langsyntaxhighlight>
 
{{works with|Bourne Shell}}
 
<langsyntaxhighlight lang="bash">max() {
m=$1 # Bourne Shell has no local command.
shift
Line 4,321 ⟶ 4,561:
done
echo "$m"
}</langsyntaxhighlight>
 
=={{header|Ursa}}==
The <code>max</code> function:
<langsyntaxhighlight lang="ursa">def max (int<> list)
decl int max i
set max list<0>
Line 4,336 ⟶ 4,576:
return max
end max</langsyntaxhighlight>
 
In use: (assuming the function is in the file <code>max.u</code>)
Line 4,353 ⟶ 4,593:
case it is used with <code>fleq</code>, the partial order relation on floating point
numbers.
<langsyntaxhighlight Ursalalang="ursala">#import flo
 
#cast %e
 
example = fleq$^ <-1.,-2.,0.,5.,4.,6.,1.,-5.></langsyntaxhighlight>
{{Out}}
<pre>6.000000e+00</pre>
Line 4,363 ⟶ 4,603:
=={{header|V}}==
Assuming it is a list of positive numbers
<langsyntaxhighlight lang="v">[4 3 2 7 8 9] 0 [max] fold
=9</langsyntaxhighlight>
 
If it is not
<langsyntaxhighlight lang="v">[4 3 2 7 8 9] dup first [max] fold</langsyntaxhighlight>
=9
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 4,386 ⟶ 4,626:
Next i
Max_VBA = temp
End Function</langsyntaxhighlight>
 
{{Out}}
Line 4,392 ⟶ 4,632:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function greatest_element(arr)
tmp_num = 0
Line 4,406 ⟶ 4,646:
 
WScript.Echo greatest_element(Array(1,2,3,44,5,6,8))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,414 ⟶ 4,654:
 
for numbers (not floats):
<langsyntaxhighlight lang="vim">max([1, 3, 2])</langsyntaxhighlight>
result: 3
 
for strings (with configurable ignore-case):
<langsyntaxhighlight lang="vim">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, '>') : '>'
Line 4,430 ⟶ 4,670:
let idx = 1
while idx < len
if eval(cmp_expr)
let maxval = a:list[idx]
endif
let idx += 1
endwhile
return maxval
endfunction</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
<langsyntaxhighlight lang="vb">Public Function ListMax(anArray())
'return the greatest element in array anArray
'use LBound and UBound to find its length
Line 4,459 ⟶ 4,699:
'print the greatest element
Debug.Print "Greatest element is"; ListMax(b())
End Sub</langsyntaxhighlight>
 
Result:
<pre>ListMaxTest
Greatest element is 5992424433449</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn max<T>(list []T) T {
mut max := list[0]
for i in 1..list.len {
if list[i] > max {
max = list[i]
}
}
return max
}
fn main() {
println('int max: ${max<int>([5,6,4,2,8,3,0,2])}')
println('float max: ${max<f64>([1e4, 1e5, 1e2, 1e9])}')
}</syntaxhighlight>
{{out}}
<pre>int max: 8
float max: 1e9</pre>
 
=={{header|Wart}}==
Wart defines <code>max</code> in terms of the more general <code>best</code>.
<langsyntaxhighlight lang="python">def (best f seq)
if seq
ret winner car.seq
Line 4,475 ⟶ 4,733:
 
def (max ... args)
(best (>) args)</langsyntaxhighlight>
 
<code>(&gt;)</code> is <code>&gt;</code> while suppressing infix expansion.
 
=={{header|WDTE}}==
<langsyntaxhighlight lang="wdte">let s => import 'stream';
let a => import 'arrays';
 
Line 4,487 ⟶ 4,745:
-> s.extent 1 >
-> at 0
;</langsyntaxhighlight>
 
<code>extent</code> is a standard library function that returns a sorted list of the elements of a stream that fit the given function best, so <code>&gt;</code> results in the maximum element.
Line 4,493 ⟶ 4,751:
=={{header|Wortel}}==
The <code>@maxl</code> returns the maximum value of a list:
<langsyntaxhighlight lang="wortel">@maxl [1 6 4 6 4 8 6 3] ; returns 8</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var max = Fn.new { |a| a.reduce { |m, x| (x > m) ? x : m } }
 
var a = [42, 7, -5, 11.7, 58, 22.31, 59, -18]
System.print(max.call(a))</langsyntaxhighlight>
 
{{out}}
Line 4,509 ⟶ 4,767:
The set of values is the lengths of the lines of text in the input file.
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \include 'code' declarations
 
def Tab=$09, LF=$0A, CR=$0D, EOF=$1A;
Line 4,536 ⟶ 4,794:
until C = EOF;
Text(0, "Longest line = "); IntOut(0, Max); CrLf(0);
]</langsyntaxhighlight>
 
Example of running the program on its source code:
Line 4,548 ⟶ 4,806:
 
The desired value is the first in a sequence that has been sorted numerically in descending order.
<langsyntaxhighlight lang="xml"><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
 
Line 4,560 ⟶ 4,818:
</xsl:for-each>
</xsl:template>
</xsl:stylesheet></langsyntaxhighlight>
 
Sample input:
 
<langsyntaxhighlight lang="xml"><numbers>
<number>3</number>
<number>1</number>
<number>12</number>
<number>7</number>
</numbers></langsyntaxhighlight>
 
{{Out}}
Line 4,577 ⟶ 4,835:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">l$ = "1,1234,62,234,12,34,6"
 
dim n$(1)
Line 4,589 ⟶ 4,847:
next
 
print "Alphabetic order: ", m$, ", numeric order: ", m</langsyntaxhighlight>
 
=={{header|Yacas}}==
Input:
<langsyntaxhighlight Yacaslang="yacas">Max({1, 3, 3, 7})
Max({Pi,Exp(1)+2/5,17*Cos(6)/5,Sqrt(91/10)})
Max({1,6,Infinity})
Max({})</langsyntaxhighlight>
{{Out}}
<pre> 7
Line 4,609 ⟶ 4,867:
> max(foo)
9</pre>
 
=={{header|Zig}}==
 
'''Works with:''' 0.10.x, 0.11.x, 0.12.0-dev.1389+42d4d07ef
 
<syntaxhighlight lang="zig">/// Asserts that `input` is not empty (len >= 1).
pub fn max(comptime T: type, input: []const T) T {
var max_elem: T = input[0];
for (input[1..]) |elem| {
max_elem = @max(max_elem, elem);
}
return max_elem;
}</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">(1).max(1,2,3) //-->3
(66).max(1,2,3.14) //-->66</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="zkl">(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</langsyntaxhighlight>
For other object types, you could use:
<langsyntaxhighlight lang="zkl">fcn max{ vm.arglist.reduce(fcn(p,n){ if(p < n) n else p }) }</langsyntaxhighlight>
<pre>max(2,1,-40,50,2,4,2) //-->50
max(2) //-->2
Line 4,626 ⟶ 4,897:
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: max
case: 1
Line 4,634 ⟶ 4,905:
input: [1,5,3,2,7]
output: 7
</syntaxhighlight>
</lang>
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 PRINT "Values"''
20 LET z=0
30 FOR x=1 TO INT (RND*10)+1
Line 4,644 ⟶ 4,915:
60 LET z=(y AND y>z)+(z AND y<z)
70 NEXT x
80 PRINT '"Max. value = ";z</langsyntaxhighlight>
Anonymous user