Greatest element of a list: Difference between revisions
Content deleted Content added
add gwbasic |
PascalABC.NET |
||
(48 intermediate revisions by 34 users not shown) | |||
Line 9:
=={{header|11l}}==
11l already has a "Maximum Value" function.
<syntaxhighlight lang
=={{header|8th}}==
<
[ 1.0, 2.3, 1.1, 5.0, 3, 2.8, 2.01, 3.14159 ] ' n:max 0 a:reduce . cr
</syntaxhighlight>
Output: 5
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight 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>
{{Output}}
<pre>
Line 147:
=={{header|ACL2}}==
<
(if (endp (rest xs))
(first xs)
(max (first xs)
(maximum (rest xs)))))</
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC Max(BYTE ARRAY tab BYTE size)
BYTE i,res
res=tab(0)
FOR i=1 TO size-1
DO
IF res<tab(i) THEN
res=tab(i)
FI
OD
RETURN (res)
PROC Main()
BYTE i,m,size=[20]
BYTE ARRAY tab(size)
FOR i=0 TO size-1
DO
tab(i)=Rand(0)
OD
Print("Array:")
FOR i=0 TO size-1
DO
PrintF(" %I",tab(i))
OD
PutE()
m=Max(tab,size)
PrintF("Greatest: %I%E",m)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Greatest_element_of_a_list.png Screenshot from Atari 8-bit computer]
<pre>
Array: 106 182 121 251 21 244 46 157 228 251 173 50 106 126 193 230 88 117 114 120
Greatest: 251
</pre>
=={{header|ActionScript}}==
<
{
var curMax:Number = -Infinity;
Line 160 ⟶ 199:
curMax = Math.max(curMax, args[i]);
return curMax;
}</
=={{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.
<
procedure Max_Test isco
Line 191 ⟶ 230:
begin
Ada.Text_IO.Put_Line(Float'Image(Max(Buf)));
end Max_Test;</
A generic function Max to deal with any floating-point type.
<
type Item is digits <>;
type Items_Array is array (Positive range <>) of Item;
function Generic_Max (List : Items_Array) return Item;</
Implementation of:
<
Result : Item := List (List'First);
begin
Line 205 ⟶ 244:
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.
=={{header|Aime}}==
<
lmax(list l)
{
Line 223 ⟶ 262:
max;
}</
or
<
lmax(list l)
{
Line 234 ⟶ 273:
max;
}</
=={{header|ALGOL 68}}==
Line 241 ⟶ 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}}
<
MODE FLT = REAL;
Line 270 ⟶ 309:
except empty array:
SKIP
)</
{{out}}
<pre>
Line 277 ⟶ 316:
=={{header|ALGOL W}}==
<
% simple list type %
record IntList( integer val; reference(IntList) next );
Line 303 ⟶ 342:
write( maxElement( IntList( -767, IntList( 2397, IntList( 204, null ) ) ) ) )
end.</
{{out}}
<pre>
2397
</pre>
=={{header|Amazing Hopper}}==
Version 1:
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
main:
lst=0
max=0
file="datos.txt"
{","} toksep
{file} statsfile
{file} load
mov (lst)
{0} reshape (lst)
{lst} array (SORT)
[end] get (lst)
mov (max)
{"Maximo = "}
{max}
{"\n"} print
exit(0)
</syntaxhighlight>
Version 2:
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
#define SIZE_LIST 100000
main:
lst=-1
max=0
{SIZE_LIST} rand array (lst)
mul by (SIZE_LIST)
mov (lst)
{lst} array (SORT)
[end] get (lst)
mov (max)
{"Maximo = "}
{max}
{"\n"} print
exit(0)
</syntaxhighlight>
{{out}}
<pre>
Maximo = 99999.8
</pre>
=={{header|AntLang}}==
<syntaxhighlight lang
=={{header|APL}}==
<
⌈/LIST</
{{out}} <pre>8</pre>
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">
max({1, 2, 3, 4, 20, 6, 11, 3, 9, 7})
Line 328 ⟶ 412:
return _curMax
end max
</syntaxhighlight>
Line 335 ⟶ 419:
{{trans|JavaScript}}
<syntaxhighlight lang="applescript">
-- maximumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a
on maximumByMay(f, xs)
Line 485 ⟶ 569:
end script
end if
end mReturn</
{{Out}}
<
=={{header|Applesoft BASIC}}==
<
110 R$ = "":E$ = ""
120 L = LEN (L$)
Line 509 ⟶ 593:
270 R = VAL (V$)
280 IF R < V THEN RETURN
290 R$ = V$: RETURN</
<
GOSUB 100MAX
PRINT R$</
{{Out}}
<pre>20</pre>
Line 518 ⟶ 602:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 731 ⟶ 815:
</syntaxhighlight>
=={{header|Arturo}}==
<
print max arr</
{{out}}
Line 744 ⟶ 828:
=={{header|AutoHotkey}}==
=== CSV Data ===
<
Loop Parse, list, `,
x := x < A_LoopField ? A_LoopField : x
MsgBox Max = %x%</
=== Pseudo-arrays ===
<
StringSplit, list, list,`, ; creates a pseudo-array
Loop % List0
x := x < List%A_Index% ? List%A_Index% : x
MsgBox Max = %x%</
=== True arrays ===
{{works with|AutoHotkey_L}}
<
For each, value in List
x := x < value ? value : x
MsgBox Max = %x%</
=={{header|AWK}}==
One-liner:
<
42</
More readable version:
<
# Usage: awk -f greatest_list_element.awk
#
Line 780 ⟶ 864:
print max(a)
}
</syntaxhighlight>
=={{header|Axe}}==
This example assumes the array is null-terminated so that the program can stop at the end of the data.
<
0→M
While {r₁}
Line 790 ⟶ 874:
End
M
Return</
=={{header|BASIC}}==
{{works with|QBasic}}
<
DECLARE FUNCTION findMax% ()
Line 840 ⟶ 924:
NEXT
findMax = tmp2
END FUNCTION</
{{Out}}
Line 848 ⟶ 932:
==={{header|BaCon}}===
<
' Populate sample array of numbers
READ elements
Line 869 ⟶ 953:
NEXT
RETURN mx
END FUNCTION</
{{out}}
Line 876 ⟶ 960:
'''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}}
<syntaxhighlight lang="freebasic">l$ = "1,1234,62,234,12,34,6"
dim n$(1)
n$ = explode(l$, ",")
m$ = "" : m = 0
for i = 1 to n$[?]-1
t$ = n$[i]
if t$ > m$ then m$ = t$
if int(t$) > m then m = int(t$)
next i
print "Alphabetic order: "; m$; ", numeric order: "; m</syntaxhighlight>
==={{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|SmallBASIC}}===
<syntaxhighlight lang="qbasic">
list = [1,1234,62,234,12,34,6]
print max(list)
</syntaxhighlight>
=={{header|Batch File}}==
<
@echo off
setlocal enabledelayedexpansion
Line 894 ⟶ 1,064:
if "%2" equ "" goto :eof
if %2 gtr !%1! set res=%2
goto loop</
''Invocation from command line or from internal prompt''
<
234243
>max
Input stream: 5 4 3 2 67 1
67</
=={{header|BBC BASIC}}==
<
PRINT "Maximum value = " ; FNmax(ListOfValues$)
END
Line 918 ⟶ 1,088:
IF number > max THEN max = number
UNTIL index% = 0
= max</
=={{header|bc}}==
<
auto m, i
Line 929 ⟶ 1,099:
}
return(m)
}</
=={{header|Befunge}}==
<
>&:01g`#v_1+#^_01g.@
^p10 <</
Only works with positive integers. List must be terminated with -1.
=={{header|BQN}}==
<syntaxhighlight lang
{{out}}
Line 949 ⟶ 1,119:
=={{header|Bracmat}}==
When comparing two rational numbers, Bracmat compares numerically. In all other cases Bracmat compares lexically.
<syntaxhighlight lang="text"> ( biggest
= max
. !arg:
Line 962 ⟶ 1,132:
biggest
$ (5 100000 -5 43756243978569758/13 3365864921428443 87512487957139516/27 3446)
)</
{{Out}}
<pre>1: mies
Line 970 ⟶ 1,140:
=={{header|Brat}}==
Arrays have a max function, but here's a manual implementation.
<
list.reduce { n, max |
true? n > max
Line 978 ⟶ 1,148:
}
p max [3 4 1 2]</
=={{header|Burlesque}}==
<
blsq ) {88 99 77 66 55}>]
99
</syntaxhighlight>
=={{header|C}}==
This works well with floats. Replace with double, int or what-have-you before passing a different data type.
<
float max(unsigned int count, float values[]) {
Line 999 ⟶ 1,169:
}
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). <!-- 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}}
<
#define MAX(A,...) ({ inline __typeof__ (A) _max_(__typeof__ (A) a, ...) {\
Line 1,017 ⟶ 1,187:
}\
_max_((A),__VA_ARGS__);\
})</
=={{header|C sharp|C#}}==
Line 1,023 ⟶ 1,193:
C# already has a "Maximum Value" function.
<
int max = values.Max();</
=={{header|C++}}==
A simple wrapper around the standard library function <tt>max_element()</tt>.
Requires C++17.
<
#include <iterator> //std::begin and std::end
#include <functional> //std::less
Line 1,049 ⟶ 1,219:
using std::begin; using std::end;
return max_value(begin(container), end(container), compare);
}</
=={{header|CFEngine}}==
Note: CFEngine bundles are NOT functions, however they can behave in some ways that are similar to functions.
<syntaxhighlight lang="cfengine3">
bundle agent __main__
{
vars:
"number_of_list_elements"
int => randomint( "0", 100 ),
unless => isvariable( "$(this.promiser)" );
"idx"
slist => expandrange( "[0-$(number_of_list_elements)]", 1 ),
unless => isvariable( "$(this.promiser)" );
"number[$(idx)]"
int => randomint( "0", "100" ),
unless => isvariable( "$(this.promiser)" );
"numbers" slist => sort( getvalues( number ), int );
methods:
"Get the greatest value"
usebundle => greatest_value( @(numbers) ),
useresult => "returned";
reports:
"'$(returned[max])' is the largest number in $(with)"
with => join( ",", numbers );
}
bundle agent greatest_value(list_of_values)
{
reports:
"$(with)"
with => max( list_of_values, int ),
bundle_return_value_index => "max";
}
</syntaxhighlight>
{{output}}
<pre>
R: '97' is the largest number in 3,5,6,13,15,30,34,37,47,49,49,53,54,59,59,59,60,62,64,67,78,83,95,97
</pre>
=={{header|Clojure}}==
The Clojure.core function max returns the max of its arguments.
<
;; If the values are already in a collection, use apply:
(apply max [1 2 3 4]) ; evaluates to 4</
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This "maximum" procedure is fully general, as long as
% the container type has an elements iterator and the
% data type is comparable.
% It raises an exception ("empty") if there are no elements.
maximum = proc [T,U: type] (a: T) returns (U)
signals (empty)
where T has elements: itertype (T) yields (U),
U has gt: proctype (U,U) returns (bool)
max: U
seen: bool := false
for item: U in T$elements(a) do
if ~seen cor item > max then
max := item
seen := true
end
end
if (~seen) then
signal empty
else
return(max)
end
end maximum
start_up = proc ()
po: stream := stream$primary_output()
% try it on an array of ints
ints: array[int] := array[int]$[1,5,17,2,53,99,61,3]
imax: int := maximum[array[int], int](ints)
stream$putl(po, "maximum int: " || int$unparse(imax))
% try it on a sequence of reals
reals: sequence[real] := sequence[real]$[-0.5, 2.6, 3.14, 2.72]
rmax: real := maximum[sequence[real], real](reals)
stream$putl(po, "maximum real: " || real$unparse(rmax))
end start_up</syntaxhighlight>
{{out}}
<pre>maximum int: 99
maximum real: 3.140000e+00</pre>
=={{header|CMake}}==
Only for lists of integers.
<
# integers. If list is empty, sets var to NO.
function(max var)
Line 1,078 ⟶ 1,340:
set(list 33 11 44 22 66 55)
max(maximum ${list})
message(STATUS "maximum of ${list} => ${maximum}")</
<pre>-- maximum of 33;11;44;22;66;55 => 66</pre>
Line 1,084 ⟶ 1,346:
=={{header|COBOL}}==
This is already built into the language for tables of numbers.
<
A sample implementation:
<
FUNCTION-ID. greatest-elt.
Line 1,111 ⟶ 1,373:
GOBACK
.
END FUNCTION greatest-elt.</
=={{header|CoffeeScript}}==
<
# using Math library
max1 = (list) ->
Line 1,131 ⟶ 1,393:
a = [0,1,2,5,4];
alert(max1(a)+". The answer is "+max2(a));
</syntaxhighlight>
=={{header|ColdFusion}}==
<
<Cfset theList = '1, 1000, 250, 13'>
<Cfparam name="maxNum" default=0>
Line 1,141 ⟶ 1,403:
</Cfloop>
<Cfoutput>#maxNum#</Cfoutput>
</syntaxhighlight>
<
<Cfset theList = '1, 1000, 250, 13'>
<Cfset maxNum = ListFirst(ListSort(thelist, "numeric", "desc"))>
<Cfoutput>#maxNum#</Cfoutput>
</syntaxhighlight>
=={{header|Common Lisp}}==
The built-in Common Lisp function <tt>max</tt> takes the max of all its arguments.
<
(reduce #'max values) ; find max of a list
(loop for x in values
maximize x) ; alternative way to find max of a list</
=={{header|Component Pascal}}==
BalckBox Component Builder
<
MODULE Operations;
IMPORT StdLog,Args,Strings;
Line 1,192 ⟶ 1,454:
END Operations.
</syntaxhighlight>
Execute: ^Q Operations..DoMax 23 12 3 45 34 54 84 ~<br/>
{{Out}}
Line 1,200 ⟶ 1,462:
=={{header|Crystal}}==
<syntaxhighlight lang
=={{header|D}}==
Line 1,206 ⟶ 1,468:
D already has a "Maximum Element" function.
<
{
import std.algorithm.searching : maxElement;
Line 1,212 ⟶ 1,474:
[9, 4, 3, 8, 5].maxElement.writeln;
}</
{{out}}
<pre>9</pre>
=={{header|Dart}}==
<
num findGreatestElement(List<num> list){
num greatestElement = list[0];
Line 1,232 ⟶ 1,494:
return list.reduce(max);
}
</syntaxhighlight>
=={{header|dc}}==
<
[lm p q] sq
[d lm <u s_ z 0 =q llx] sl
Line 1,246 ⟶ 1,508:
_275.0 _111.19 0.0 _1234568.0 lp lp _1 *
lgx</
{{Out}}
Line 1,252 ⟶ 1,514:
=={{header|DCL}}==
<
$ max = f$integer( f$element( 0, ",", list ))
$ i = 1
Line 1,263 ⟶ 1,525:
$ goto loop
$ done:
$ show symbol max</
{{out}}
<pre>$ @greatest
Line 1,269 ⟶ 1,531:
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
program GElemLIst;
{$IFNDEF FPC}
Line 1,293 ⟶ 1,555:
writeln(Math.MaxValue(fltArr));
end.
</syntaxhighlight>
=={{header|Dyalect}}==
<
var y
for x in xs {
Line 1,307 ⟶ 1,569:
var xs = [1..10]
max(xs)</
=={{header|Déjà Vu}}==
<
lst! 0
for item in copy lst:
Line 1,316 ⟶ 1,578:
item drop
!. max [ 10 300 999 9 ]</
{{out}}
<pre>999</pre>
=={{header|Draco}}==
<syntaxhighlight lang="draco">/* Find the greatest element in an array of ints */
proc nonrec max([*] int a) int:
int INT_MIN = ~((~0) >> 1);
int nmax, i;
nmax := INT_MIN;
for i from 0 upto dim(a,1)-1 do
if a[i] > nmax then nmax := a[i] fi
od;
nmax
corp
/* Test on an array */
proc nonrec main() void:
type arr = [8] int;
writeln("Maximum: ", max(arr(1,5,17,2,53,99,61,3)))
corp</syntaxhighlight>
{{out}}
<pre>Maximum: 99</pre>
=={{header|E}}==
Line 1,324 ⟶ 1,606:
This function works for any value which responds to <code>[http://wiki.erights.org/wiki/Category:Message_max/1 max/1]</code>:
<
def max([first] + rest) {
return accum first for x in rest { _.max(x) }
}</
<
# value: 3</
To require only the comparison protocol, one needs to write out the algorithm a little more explicitly:
<
for x ? (x > bestSoFar) in rest {
bestSoFar := x
}
return bestSoFar
}</
<
# value: 3
? max([[1].asSet(), [2].asSet(), [1, 2].asSet()])
# value: [1, 2].asSet()</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">a[] = [ 2 9 4 3 8 5 ]
for
.
print max</
=={{header|EchoLisp}}==
<
;; a random length list of random values
(define L (map random (make-list (random 50) 100))) → L
Line 1,366 ⟶ 1,646:
;; find max
(apply max L) → 97
</syntaxhighlight>
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
MaxVal(SET OF INTEGER s) := MAX(s);
Line 1,376 ⟶ 1,656:
SetVals := [4,8,16,2,1];
MaxVal(SetVals) //returns 16;
</syntaxhighlight>
=={{header|Efene}}==
<
list_max(Rest, Head)
}
Line 1,403 ⟶ 1,683:
io.format("~p~n", [list_max1([9, 4, 3, 8, 5])])
}
</syntaxhighlight>
=={{header|Eiffel}}==
The GREATEST_ELEMENT class:
<
class
GREATEST_ELEMENT [G -> COMPARABLE]
Line 1,448 ⟶ 1,728:
end
</syntaxhighlight>
A test application:
<
class
APPLICATION
Line 1,471 ⟶ 1,751:
end
</syntaxhighlight>
=={{header|Ela}}==
<
findBy p (x::xs) = foldl (\x y | p x y -> x | else -> y) x xs
maximum = findBy (>)
maximum [1..10]</
=={{header|Elena}}==
ELENA
<
extension op
Line 1,495 ⟶ 1,775:
while (en.next())
{
var item := *en
if (nil == maximal)
{
Line 1,513 ⟶ 1,793:
{
console.printLine(new int[]{1,2,3,4,20,10,9,8}.Maximal)
}</
{{out}}
<pre>
Line 1,520 ⟶ 1,800:
=={{header|Elixir}}==
<
9</
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun find-maximum (items)
(dolist (item items)
(when (or (not max) (> item max))
(find-maximum '(2 7 5)) ;=> 7</syntaxhighlight>
<syntaxhighlight lang="lisp">(max '(2 7 5)) ;=> 7</syntaxhighlight>
{{libheader|cl-lib}}
<syntaxhighlight lang="lisp">(cl-loop for el in '(2 7 5) maximize el) ;=> 7
(cl-reduce #'max '(2 7 5)) ;=> 7</syntaxhighlight>
{{libheader|seq.el}}
<syntaxhighlight lang="lisp">(seq-max '(2 7 5)) ;=> 7</syntaxhighlight>
=={{header|Erlang}}==
Builtin. Using it from the Erlang shell:
<
9</
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM MAXLIST
Line 1,570 ⟶ 1,857:
PRINT("Max list element is";MAX)
END PROGRAM
</syntaxhighlight>
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 <- ` '''formal''' ls;
'''begin''' '''new''' L; '''new''' i; '''new''' result; '''label''' iLoop;
L <- ls;
result <- '''undefined''';
i <- 0;
iLoop: '''if''' [ i <- i + 1 ] <= '''length''' L '''then''' '''begin'''
'''if''' '''isu''' result '''or''' '''real''' L[ i ] > '''real''' result
'''then''' result <- L[ i ] '''else''' 0;
'''goto''' iLoop
'''end''' '''else''' 0;
result
'''end'''
';
'''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>
=={{header|Euphoria}}==
===Applying a function to each element of an array===
<
for i = 1 to length( sArr ) do
sArr[ i ] = call_func( id, { sArr[ i ] } )
Line 1,607 ⟶ 1,913:
biggun = "ant"
a = aeval( s, routine_id("biggest") )
printf( 1, "%s\n", {biggun} )</
{{Out}}
<pre>
Line 1,615 ⟶ 1,921:
===More trivial example===
<
object biggun
biggun = s[1]
Line 1,630 ⟶ 1,936:
constant animals = {"ant", "antelope", "dog", "cat", "cow", "wolf", "wolverine", "aardvark"}
printf(1,"%s\n",{get_biggest(animals)})</
{{Out}}
Line 1,641 ⟶ 1,947:
Use the function MAX
<syntaxhighlight lang="excel">
=MAX(3;2;1;4;5;23;1;2)
</syntaxhighlight>
{{out}}
<pre>
Line 1,653 ⟶ 1,959:
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.
<
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>
{{out}}
<pre>
Line 1,667 ⟶ 1,973:
=={{header|Factor}}==
The following word is in factor's standard library.
<
=={{header|Fancy}}==
<
=={{header|Fantom}}==
Line 1,676 ⟶ 1,982:
Has a built-in method to get maximum from a list.
<
class Greatest
{
Line 1,686 ⟶ 1,992:
}
}
</syntaxhighlight>
=={{header|Forth}}==
<
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 ;</
=={{header|Fortran}}==
Line 1,701 ⟶ 2,007:
The intrinsic function <tt>maxval</tt> returns the maximum value of the elements in an integer or real array:
<
integer,dimension(5),parameter :: x = [10,100,7,1,2]
Line 1,709 ⟶ 2,015:
write(*,'(F5.1)') maxval(y)
end program test_maxval</
{{Out}}
Line 1,719 ⟶ 2,025:
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.
<
implicit none
Line 1,740 ⟶ 2,046:
& max (['abc', 'hig', 'fde'], ['ghi', 'efd', 'cab'], ['def', 'bca', 'igh'])
end program test_max</
{{Out}}
<pre>
Line 1,754 ⟶ 2,060:
=={{header|FreeBASIC}}==
<
Function MaxElement(a() As Double) As Double
Line 1,778 ⟶ 2,084:
Print "Press any key to quit"
Sleep
</syntaxhighlight>
Example of use :
Line 1,793 ⟶ 2,099:
=={{header|Frink}}==
<
println[max[[1,2,3,5,10,20]]]
</syntaxhighlight>
=={{header|FunL}}==
Using the pre-defined function <code>max</code>:
<
{{out}}
<pre>
Line 1,806 ⟶ 2,112:
It can be implemented as:
<
maximum( xs ) =
def
Line 1,817 ⟶ 2,123:
foldl1( _, [] ) = error( "foldl1: empty list" )
foldl1( max, xs )</
=={{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>
=={{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}}
'''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]]
[[File:Fōrmulæ - Greatest element of a list 06.png]]
=={{header|GW-BASIC}}==
<
20 DIM ARR(N%)
30 FOR I% = 0 TO N%-1
Line 1,845 ⟶ 2,208:
100 NEXT I%
110 PRINT "The maximum value was ";CHAMP;" at index ";INDEX;"."
120 END</
=={{header|GAP}}==
<
L := List([1 .. 100], n -> Random(1, 10));
MaximumList(L);
# 10</
=={{header|Go}}==
;Library
::<
import (
Line 1,868 ⟶ 2,231:
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
}</
::<
import "fmt"
Line 1,893 ⟶ 2,256:
fmt.Println("The biggest number is ", biggest) // prt 97
fmt.Println("The smallest number is ", smallest) // prt 9
}</
;List
The task title says list. This solution uses a Go slice as a list.
<
import (
Line 1,933 ⟶ 2,296:
fmt.Println("empty list. no maximum.")
}
}</
;Set
The task description says set. This solution uses a Go map as a set.
<
import (
Line 1,999 ⟶ 2,362:
fmt.Println("no largest, empty set")
}
}</
=={{header|Golfscript}}==
<
[1 4 8 42 6 3]max # Example usage</
=={{header|Groovy}}==
<
{{Out}}
Line 2,013 ⟶ 2,376:
=={{header|Haskell}}==
The built-in Haskell function <tt>maximum</tt> returns a maximum based on default comparison between members of an ordered type.
<
It can alternately be defined as a "fold" on the built-in two-argument <tt>max</tt> function.
<
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:
<
import Data.Ord (comparing)
Line 2,025 ⟶ 2,388:
main :: IO ()
main = print $ maximumBy (comparing length) wds</
As a fold, maximumBy could be defined along the lines of:
<
:: Foldable t
=> (a -> a -> Ordering) -> t a -> a
Line 2,037 ⟶ 2,400:
GT -> x
_ -> y
in foldr1 max_</
=={{header|hexiscript}}==
<
let l len a
let max a[0]
Line 2,049 ⟶ 2,412:
endfor
return max
endfun</
=={{header|HicEst}}==
<
max_value = MAX( -123, 234.56, 345.678, -456E3, -455) ! built-in function MAX(...)
Line 2,075 ⟶ 2,438:
! 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>
=={{header|Hoon}}==
<
|= [^ [a=(list ,@) ~] ~]
:- %noun
(snag 0 (sort a gte))</
Usage: Add to a file gen/max.hoon
<pre>
Line 2,089 ⟶ 2,452:
=={{header|i}}==
<
large = l[0]
for element in l
Line 2,101 ⟶ 2,464:
software {
print(largest([23, 1313, 21, 35757, 4, 434, 232, 2, 2342]))
}</
=={{header|Icon}} and {{header|Unicon}}==
<
local l
l := [7,8,6,9,4,5,2,3,1]
Line 2,115 ⟶ 2,478:
every max <:= !l
return max
end</
=={{
<code>max</code> is a built-in operation.
<syntaxhighlight lang="insitux">
;or
(... max [1 2 3 4])
</syntaxhighlight>
{{out}}
<pre>
4
</pre>
=={{header|J}}==
'''Solution''':<syntaxhighlight lang
'''Example''':<
3
>./'' NB. Maximum value of an empty list = identity element (or neutral) of max = -∞
__</
(J's lists know how long they are.)
=={{header|Janet}}==
<
(def elems @[3 1 3 2])
Line 2,142 ⟶ 2,514:
# Unpack list as arguments to max function.
(max ;elems)
</syntaxhighlight>
=={{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.
<
if (values.length == 0)
throw new NoSuchElementException();
Line 2,155 ⟶ 2,536:
}
return themax;
}</
Optionally, if it is OK to rearrange the contents of the original array:
<
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 <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.
<
import java.util.Collections;
import java.util.Arrays;
Line 2,176 ⟶ 2,557:
public static <T extends Comparable<? super T>> T max(T[] values) {
return Collections.max(Arrays.asList(values));
}</
=={{header|JavaScript}}==
===ES3-5===
<
===ES 5 maxima beyond simple numeric data types===
Line 2,186 ⟶ 2,567:
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.
<
// (a -> a -> Ordering) -> [a] -> a
Line 2,278 ⟶ 2,659:
]
})();</
{{Out}}
<syntaxhighlight lang="javascript">[
"alpha",
"zeta",
Line 2,303 ⟶ 2,684:
"population": 13.3
}
]</
===ES6===
For, numbers, a method of the standard Math object:
<
and for orderings defined over other datatypes:
<
//
//
// [a]
// Nothing,
// or just the maximum value when compared
// in terms of f.
xs
) : x,
xs[0]
))
) : Nothing();
//
const main = () =>
JSON.stringify(
catMaybes([
maximumByMay(
comparing(x => x.length)
)([
"alpha", "beta", "gamma", "delta",
"epsilon", "zeta", "eta"
]),
maximumByMay(comparing(x => x.length))([]),
maximumByMay(comparing(x => x.n))([{
k: "Bejing",
n: 21.5
}, {
k: "Delhi",
n: 16.7
}, {
k: "Karachi",
n: 23.5
}, {
k: "Lagos",
n: 16.0
}, {
k: "Shanghai",
n: 24.3
}, {
k: "Tokyo",
n: 13.2
}])
]),
null, 2
);
// --------------------- GENERIC ---------------------
//
const
type: "Maybe",
Nothing: false,
Just: x
});
//
const
});
//
) : [m.Just]
);
//
const
x => y => {
const
a = f(x),
b = f(y);
return a < b ? -1 : (a > b ? 1 : 0);
return
})();</syntaxhighlight>
{{Out}}
<pre>[
Line 2,412 ⟶ 2,793:
}
]</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:
<
[ {"a": 1}, {"a":3}, {"a":1.0}] | max # => {"a": 3}</
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:
<
=={{header|Julia}}==
Using the built-in <code>maximum</code> function:
<
7
Line 2,438 ⟶ 2,822:
at In[138]:1
in maximum at abstractarray.jl:1591
</syntaxhighlight>
(Note that it throws an exception on an empty array.)
=={{header|K}}==
<
7</
=={{header|Klingphix}}==
<
( "1" "1234" "62" "234" "12" "34" "6" )
Line 2,458 ⟶ 2,842:
"Numeric order: " print lmax ?
" " input</
=={{header|Klong}}==
<
|/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</
{{out}}
<pre>77
Line 2,472 ⟶ 2,856:
=={{header|Kotlin}}==
Kotlin
<syntaxhighlight lang="kotlin">
fun main() {
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">
1) using the builtin primitive
Line 2,520 ⟶ 2,890:
{my-max {A.new 556 1 7344 4 7 52 22 55 88 122 55 99 1222 578}}
-> 7344
</syntaxhighlight>
=={{header|Lasso}}==
<
return (#a->sort&)->last
}
local(x = array(556,1,7344,4,7,52,22,55,88,122,55,99,1222,578))
greatest(#x)</
{{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:
<
9</
=={{header|Liberty BASIC}}==
<
maxVal = val(word$(aList$, 1))
Line 2,550 ⟶ 2,960:
wend
print "maxVal = ";maxVal</
=={{header|Lingo}}==
<
put max(l)
-- 7</
=={{header|LiveCode}}==
Max is built-in<
Result: 7
To be fair to the exercise, an alternative implementation could be<
local maxNum
put item 1 of lst into maxNum
Line 2,574 ⟶ 2,984:
on mouseUp
answer max2("1,2,5,6,7,4,3,2")
end mouseUp</
=={{header|Logo}}==
Line 2,582 ⟶ 2,992:
to use APPLY instead of REDUCE. The latter is good for associative
procedures that have been written to accept exactly two inputs:
<
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:
<
if emptyp :inputs ~
[(throw "error [not enough inputs to max])]
output reduce [ifelse ?1 > ?2 [?1] [?2]] :inputs
end</
{{works with|UCB Logo}}
<
output ifelse [greater? :a :b] [:a] [:b]
end
Line 2,602 ⟶ 3,012:
to max :lst
output reduce "bigger :lst
end</
=={{header|Logtalk}}==
<
max([X| Xs], Max) :-
max(Xs, X, Max).
Line 2,614 ⟶ 3,024:
max(Xs, X, Max)
; max(Xs, Aux, Max)
).</
=={{header|Lua}}==
<
local values = {}
-- Read in the first number from stdin
Line 2,630 ⟶ 3,040:
-- Print the max
print(math.max(unpack(values)))
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module TestThis {
Print "Search a tuple type list (is an array also)"
Line 2,710 ⟶ 3,120:
}
TestThis
</syntaxhighlight>
=={{header|Maple}}==
This is a built-in, polymorphic procedure in Maple.
<
Pi
Line 2,724 ⟶ 3,134:
> 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.
<
11</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Input:
<
Max[Pi,E+2/5,17 Cos[6]/5,Sqrt[91/10]]
Max[1,6,Infinity]
Max[]</
{{Out}}
<pre> 7
Line 2,741 ⟶ 3,151:
-Infinity</pre>
Note that Max returns minus infinity if supplied with no arguments; as it should:
<
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 things can happen:
<
WOULD give 0 instead of -3
=={{header|MATLAB}}==
<
maxValue = max(setOfValues);</
=={{header|Maxima}}==
<
/* Three solutions */
Line 2,761 ⟶ 3,171:
apply(max, u);
lmax(u);</
=={{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.
<
(
if AnArray.count != 0 then
Line 2,775 ⟶ 3,185:
)
else undefined
)</
=={{header|Metafont}}==
Line 2,781 ⟶ 3,191:
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).
<
show max((12,3), (10,10), (25,5));
show max("hello", "world", "Hello World");</
=={{header|min}}==
{{works with|min|0.
<syntaxhighlight lang="min">(() ('> 'pop 'nip if) map-reduce) ^max
(5 3 2 7 4) max puts!</syntaxhighlight>
=={{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.
<
if not self then return null
result = self[0]
Line 2,805 ⟶ 3,212:
end function
print [47, 11, 42, 102, 13].max</
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П0 С/П x=0 07 ИП0 x<0 00 max БП 00</
or
<syntaxhighlight lang="text">П0 ИП0 С/П - x<0 01 Вx П0 БП 01</
=={{header|Modula-3}}==
Line 2,818 ⟶ 3,225:
We provide a generic Maximum implementation:
<
EXCEPTION Empty;
Line 2,824 ⟶ 3,231:
PROCEDURE Max(READONLY a: ARRAY OF Elem.T): Elem.T RAISES {Empty};
END Maximum.</
<
PROCEDURE Max(READONLY arr: ARRAY OF Elem.T): Elem.T RAISES {Empty} =
Line 2,843 ⟶ 3,250:
BEGIN
END Maximum.</
<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:
<
<
Now we can import <code>RealMax</code> into our source and use the <code>Max</code> function:
<
IMPORT RealMax, IO, Fmt;
Line 2,860 ⟶ 3,267:
BEGIN
IO.Put(Fmt.Real(RealMax.Max(realarr)) & "\n");
END Main.</
=={{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.
<
LEN VAR l .
Line 2,875 ⟶ 3,282:
FOR st
MAX
ENDFOR PRINT</
Another way to do it.
<
print
LEN VAR l .
Line 2,891 ⟶ 3,298:
|Greatest number in the list: | out . print
|Press ENTER to exit | input
clear</
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">
MV(A,U)
;A is a list of values separated by the string U
Line 2,900 ⟶ 3,307:
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>
Usage:
<pre>
Line 2,912 ⟶ 3,319:
=={{header|Nanoquery}}==
<
if len(list) = 0
return null
Line 2,924 ⟶ 3,331:
end
return largest
end</
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
greatest element from a list (Neko Array)
Tectonics:
Line 2,950 ⟶ 3,357:
$print(greatest($array(5, 1, 3, 5)), "\n");
$print(greatest($array("abc", "123", "zyx", "def")), "\n");</
{{out}}
Line 2,959 ⟶ 3,366:
=={{header|Nemerle}}==
<
using Nemerle.Collections;
using System.Linq;
Line 2,986 ⟶ 3,393:
WriteLine($"letters.Max() = $(letters.Max())")
}
}</
{{Out}}
Line 2,995 ⟶ 3,402:
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols binary
Line 3,027 ⟶ 3,434:
end n_
return dmax
</syntaxhighlight>
{{Out}}
<pre>
Line 3,035 ⟶ 3,442:
=={{header|NewLISP}}==
<
<
; Added by Nehal-Singhal 2018-05-29</
=={{header|Nial}}==
The behavior of multi-dimensional arrays is like J
<
=4</
=={{header|Nim}}==
<
{{out}}<pre>6</pre>
Line 3,053 ⟶ 3,460:
=={{header|Oberon-2}}==
{{Works with|oo2c Version 2}}
<
MODULE GreatestElement1;
IMPORT
Line 3,092 ⟶ 3,499:
Out.String("Max: ");Out.LongInt(max.value,4);Out.Ln
END GreatestElement1.
</syntaxhighlight>
Simple version
<
MODULE GreatestElement2;
IMPORT
Line 3,122 ⟶ 3,529:
Out.String("Max: ");Out.LongInt(Max(a),4);Out.Ln
END GreatestElement2.
</syntaxhighlight>
{{out}}(in both programs):
<pre>
Line 3,130 ⟶ 3,537:
=={{header|Objeck}}==
The language has a "Max" method for vectors.
<
values := IntVector->New([4, 1, 42, 5]);
values->Max()->PrintLine();
</syntaxhighlight>
=={{header|Objective-C}}==
Line 3,153 ⟶ 3,560:
<
@interface NSArray (WithMaximum)
Line 3,175 ⟶ 3,582:
return maybeMax;
}
@end</
This example mixes integers with a double value, just to show that
everything is fine until they are NSNumber.
<
{
@autoreleasepool {
Line 3,188 ⟶ 3,595:
}
return 0;
}</
=={{header|OCaml}}==
<
[] -> invalid_arg "empty list"
| x::xs -> List.fold_left max x xs</
# my_max [4;3;5;9;2;3] ;;
Line 3,202 ⟶ 3,609:
Octave's <code>max</code> accepts a vector (and can return also the index of the maximum value in the vector)
<
[m, im] = max( [1,2,3,20,10,9,8] ); % im = 4</
=={{header|Oforth}}==
<
=={{header|Ol}}==
Basics:
<
; builtin function
(max 1 2 3 4 5) ; 5
Line 3,227 ⟶ 3,634:
(if (less? a b) b a))
(car x) x)) ; 5
</syntaxhighlight>
=={{header|ooRexx}}==
===version===
<syntaxhighlight lang="oorexx">
-- routine that will work with any ordered collection or sets and bags containing numbers.
::routine listMax
Line 3,247 ⟶ 3,654:
return largest
</syntaxhighlight>
===version 2 works with any strings===
<syntaxhighlight lang="text">/* REXX ***************************************************************
* 30.07.2013 Walter Pachl as for REXX
**********************************************************************/
Line 3,267 ⟶ 3,674:
largest = item
end
return largest</
=={{header|OxygenBasic}}==
<syntaxhighlight lang="text">
'Works on any list with element types which support '>' comparisons
macro max any(R, A, N, i)
============================
scope
indexbase 1
int i
R=A(1)
for i=2 to N
if A(i)>R
R=A(i)
endif
next
end scope
end macro
'DEMO
=====
redim double d(100)
d={ 1.1, 1.2, 5.5, -0.1, -12.0 }
double m=max(d,5)
print "greatest element of d(): " m '5.5
</syntaxhighlight>
=={{header|Oz}}==
<
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]}}</
=={{header|PARI/GP}}==
<syntaxhighlight lang
=={{header|Pascal}}==
Line 3,284 ⟶ 3,717:
{{works with | Free Pascal}}
or try this, for it shows the according position
<
{$IFNDEF FPC}
{$Apptype Console}
Line 3,384 ⟶ 3,817:
Ergflt := FindMaxflt(fltArr);
writeln('FindMaxFlt ',Ergflt.mpMax:0:4,' @ ',Ergflt.mpPos);
end.</
Out, because of the searchdirection Position of FindMaxFlt is below FindMaxInt
Line 3,390 ⟶ 3,823:
FindMaxInt 999999 @ 691620
FindMaxFlt 999999.0265 @ 14824</pre>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
##
var values := Lst(1,7,4,6,3,5,2,6);
values.Max.Print;
</syntaxhighlight>
=={{header|Perl}}==
<
my $max = shift;
for (@_) { $max = $_ if $_ > $max }
return $max;
}</
It is already implemented in the module <tt>List::Util</tt>'s <tt>max()</tt> function:
<
max(@values);</
=={{header|Phix}}==
<!--<syntaxhighlight lang="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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,413 ⟶ 3,856:
=={{header|Phixmonti}}==
<
dup "Alphabetic order: " print max print nl
Line 3,420 ⟶ 3,863:
i get tonum i set
endfor
"Numeric order: " print max print</
With syntactic sugar
<
( "1" "1234" "62" "234" "12" "34" "6" )
Line 3,437 ⟶ 3,880:
dup "Numeric order: " print max print
</syntaxhighlight>
=={{header|PHP}}==
The built-in PHP function <tt>max()</tt> already does this.
<syntaxhighlight lang
=={{header|PicoLisp}}==
<
-> 4
: (apply max (2 4 1 3)) # Apply to a list
-> 4
: (maxi abs (2 -4 -1 3)) # Maximum according to given function
-> -4</
=={{header|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;
</syntaxhighlight>
=={{header|PostScript}}==
Line 3,464 ⟶ 3,907:
{{works with|Ghostscript}}
<
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:
<
dup 0 get exch % put the first element underneath the array
{
Line 3,480 ⟶ 3,923:
pop % remove it
} forall
} def</
{{libheader|initlib}}
<
[1 2 3 4 5 4 3 2 1] uncons exch {max} fold
</syntaxhighlight>
=={{header|PowerBASIC}}==
<
DIM x AS LONG, y AS LONG, z AS LONG
RANDOMIZE TIMER
Line 3,499 ⟶ 3,942:
? STR$(z) & " was the highest value"
END FUNCTION</
{{Out}}
Line 3,508 ⟶ 3,951:
=={{header|PowerShell}}==
The <code>Measure-Object</code> cmdlet in PowerShell already has this capability:
<
return ($a | Measure-Object -Maximum).Maximum
}</
=={{header|Prolog}}==
SWI-Prolog already knows max_list.
<
M = 10.</
can be implemented like this:
<
select(V, L, R), \+((member(X, R), X > V)).
</syntaxhighlight>
=={{header|PureBasic}}==
<
Protected last, i, ret.f
Line 3,536 ⟶ 3,979:
ProcedureReturn ret
EndProcedure</
===PureBasic: another solution===
<
ForEach tl() : mx.f=mx*Bool(mx>=tl())+tl()*Bool(mx<tl()) : Next
ProcedureReturn mx
Line 3,545 ⟶ 3,988:
NewList testlist.f() : OpenConsole()
For i=0 To 99 : AddElement(testlist()) : testlist()=Sqr(Random(1000)) : Next
Print("Greatest element = "+StrF(maxelement(testlist()),8)) : Input()</
{{out}}
<pre>Greatest element = 31.59113884</pre>
=={{header|Python}}==
===Numeric values===
The built-in Python function <tt>max()</tt> already does this.
<syntaxhighlight lang
Of course this assumes we have a list or tuple (or other sequence like object). (One can even find the ''max()'' or ''min()'' character of a string since that's treated as a sequence of characters and there are "less than" and "greater than" operations (object methods) associate with those characters).
Line 3,558 ⟶ 4,002:
max(), (and min()), can take iterables and a key argument which takes a function that can transform each item into a type that we can compare, for example, if the stream were returning string representations of integers, one to a line, you could do
<
>>> max(floatstrings, key = float)
'0.01e4\n'
>>></
Normally we would want the converted form as the maximum and we could just as easily write:
<
100.0
>>></
Or you can write your own functional version, of the maximum function, using reduce and lambda
<
>>> reduce(lambda a,b: a if (a > b) else b, mylist)
102</
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}}==
<
q)max l
9</
=={{header|Quackery}}==
<
=={{header|R}}==
<
print(max(v)) # 100</
=={{header|Racket}}==
The "max" function it built in and takes an arbitrary amount of arguments.
<
{{Out}}
<pre>17</pre>
To use with a list, there is <tt>apply</tt>:
<
However, if you want to write the function yourself:
<
(define (my-max l)
(define (max-h l greatest)
Line 3,600 ⟶ 4,088:
[else (max-h (rest l) greatest)]))
(if (empty? l) empty (max-h l (first l))))
</syntaxhighlight>
or with a "for" loop:
<
(define (my-max l)
(for/fold ([max #f]) ([x l])
(if (and max (> max x)) max x)))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
The built-in function works with any type that defines ordering.
<syntaxhighlight lang="raku"
say max <zero one two three four five six seven eight nine>;
Line 3,618 ⟶ 4,106:
my @list = flat(0..9,'A'..'H').roll((^60).pick).rotor(4,:partial)».join.words;
say @list, ': ', max @list;
</syntaxhighlight>
{{out|Sample output}}
<pre>11
Line 3,625 ⟶ 4,113:
=={{header|RapidQ}}==
<
dim x as integer
Line 3,634 ⟶ 4,122:
Print FindMax(50, 20, 65, 20, 105)
</syntaxhighlight>
=={{header|Rascal}}==
Rascal has a built-in function that gives the greatest element of a list
<
rascal>import List;
ok
Line 3,644 ⟶ 4,132:
rascal>max([1,2,3,4]);
int: 4
</syntaxhighlight>
=={{header|Raven}}==
<
{{out}} <pre>4</pre>
'''Randomly generated list size and elements'''
<
[ ] as $lst
0 $cnt 1 range each drop 100 choose $lst push
$lst print
$lst max "max value: %d\n" print</
=={{header|REBOL}}==
<
Title: "Maximum Value"
URL: http://rosettacode.org/wiki/Maximum_Value
Line 3,671 ⟶ 4,159:
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]</
{{Out}}
Line 3,678 ⟶ 4,166:
=={{header|Red}}==
<
list: [1 2 3 5 4]
print last sort list
</syntaxhighlight>
=={{header|REXX}}==
The numbers in the list may be any valid REXX number (integer, negative, floating point, etc.)
===using a list===
<
$ = 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,694 ⟶ 4,182:
end /*j*/
say /*stick a fork in it, we're all done. */
say 'the biggest value in a list of ' # " numbers is: " big</
{{out|output|text= when using the default (internal) input:}}
<pre>
Line 3,703 ⟶ 4,191:
===using an array===
<
@.=; @.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,713 ⟶ 4,201:
end /*#*/
/*stick a fork in it, we're all done. */
say 'the biggest value in an array of ' #-1 " elements is: " big</
{{out|output|text= when using the default (internal) input:}}
<pre>
Line 3,720 ⟶ 4,208:
===using a list from 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,728 ⟶ 4,216:
end /*j*/
say /*stick a fork in it, we're all done. */
say '────────────────── The biggest value in the list of ' # " elements is: " big</
Programming note: the '''max''' BIF normalizes the number returned (eliding the leading superfluous zeroes).
If this is undesirable, then the '''do''' loop (shown above) can be replaced with:
<
if _>big then big=_
end /*j*/</
{{out|output|text= when using the input from the terminal via a user prompt:}}
<pre>
Line 3,744 ⟶ 4,232:
===list of any strings===
<
* If the list contains any character strings, the following will work
* Note the use of >> (instead of >) to avoid numeric comparison
Line 3,762 ⟶ 4,250:
max=word(l,i)
End
Return max</
{{out|output|text= when using an '''ASCII''' system:}}
<pre>
Line 3,780 ⟶ 4,268:
=={{header|Ring}}==
<
see max(aList)</
{{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
=={{header|Run BASIC}}==
<
while word$(list$,i+1," ") <> ""
mx = max(mx,val(word$(list$,i+1," ")))
i = i + 1
wend
print mx</
=={{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.
<
let nums = [1,2,39,34,20];
println!("{:?}", nums.iter().max());
println!("{}", nums.iter().max().unwrap());
}</
{{out}}
Line 3,813 ⟶ 4,309:
=={{header|S-lang}}==
Starting w/an array, this is trivial:
<
print(max(a));</
output:
Line 3,820 ⟶ 4,316:
If a is a list instead of an array, then:
<
print(max(list_to_array(a)));</
=={{header|Scala}}==
{{libheader|Scala}}
<
// Test
assert(noSweat(1, 3, 12, 7) == 12)</
=={{header|Scheme}}==
The built-in Scheme function <tt>max</tt> takes the max of all its arguments.
<
(apply max values) ; find max of a list</
=={{header|Seed7}}==
<
const func integer: max (in array integer: values) is func
Line 3,854 ⟶ 4,350:
begin
writeln(max([] (1, 2, 6, 4, 3)));
end func;</
{{Out}}
Line 3,864 ⟶ 4,360:
Using ''reduceWith:'' it is very simple to find the maximum value among a collection.
<
Or, since it's "built-in", you can simply do:
<
=={{header|SenseTalk}}==
<
put the highest value of [88,-2,6,55,103,0]</
Output:
<
103</
=={{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
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
Using ''fold'' it is very simple to find the maximum value among a collection.
<
Or, since it's "built-in", you can simply do:
Line 3,893 ⟶ 4,389:
{{works with|Pharo|1.4}}
{{works with|Smalltalk/X}}
<
using #inject:into:
<
| list |
list := #(1 2 3 4 20 10 9 8).
list inject: (list at: 1) into: [ :number :each |
number max: each ]
</syntaxhighlight>
=={{header|SNOBOL4}}==
<
max = gt(a,max) a :(while)
stop output = max
end</
=={{header|Standard ML}}==
Comparisons are specific for each type. Here is a max function for a list of ints:
<
| max_of_ints (x::xs) = foldl Int.max x xs</
- max_of_ints [4,3,5,9,2,3];
Line 3,921 ⟶ 4,417:
Use the '''[https://www.stata.com/help.cgi?summarize summarize]''' command to compute the maximum value of a variable:
<
di r(max)</
Mata has also several [https://www.stata.com/help.cgi?mf_minmax functions] to compute minimum or maximum of a vactor or matrix:
<
max(a)</
=={{header|Swift}}==
{{works with|Swift|2.x}}
<
print(x) // prints 9
}</
{{works with|Swift|1.x}}
<
println(x) // prints 9</
=={{header|Tailspin}}==
Simplest is to use the built-in collector
<
[1, 5, 20, 3, 9, 7] ... -> ..=Max&{by: :(), select: :()} -> !OUT::write
// outputs 20
Line 3,949 ⟶ 4,445:
sink accumulate
<?($@Max <=[]>)
| ?($(by) <$@Max
end accumulate
source result
$@Max
end result
end Max
</syntaxhighlight>
But here is how to find the max more manually/programmatically, it is pretty easy as well
<
templates max
@: $(1);
Line 3,967 ⟶ 4,463:
[1, 5, 20, 3, 9, 7] -> max -> !OUT::write
// outputs 20
</syntaxhighlight>
Can also be written as an inline templates
<
[1, 5, 20, 3, 9, 7] -> \(@: $(1); $(2..last)... -> # $@ ! when <$@..> do @: $;\) -> !OUT::write
// outputs 20
</syntaxhighlight>
Or we can do just the matching in an inline templates referencing the outer state
<
templates max
@: $(1);
Line 3,983 ⟶ 4,479:
[1, 5, 20, 3, 9, 7] -> max -> !OUT::write
// outputs 20
</syntaxhighlight>
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
Use the <code>{*}</code> expansion operator to substitute the list value with its constituent elements
<
set values {4 3 2 7 8 9}
::tcl::mathfunc::max {*}$values ;# ==> 9</
=={{header|TI-83 BASIC}}==
Line 4,000 ⟶ 4,496:
The builtin <code>max</code> function can be applied to lists. <code style="font-family:'TI Uni'">max({1, 3, 2})</code> = 3.
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
MainModule: {
_start: (λ
(textout (max 9 6 2 11 3 4) " ")
(with v [1, 45, 7, 274, -2, 34]
(textout (max-element v) " ")
(textout (max-element-idx v))
))
}</syntaxhighlight>{{out}}
<pre>
11 274 3
</pre>
=={{header|Trith}}==
<
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
LOOP n,list="2'4'0'3'1'2'-12"
Line 4,012 ⟶ 4,523:
ENDLOOP
PRINT greatest
</syntaxhighlight>
{{Out}}
<pre>
Line 4,020 ⟶ 4,531:
=={{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,033 ⟶ 4,544:
If c@ > d@ THEN d@ = c@ ' Change maximum if required
Next
Return (d@) ' Return the maximum</
=={{header|UNIX Shell}}==
Line 4,039 ⟶ 4,550:
{{works with|pdksh}}
<
local m=$1
shift
Line 4,050 ⟶ 4,561:
}
max 10 9 11 57 1 12</
{{works with|Bourne Shell}}
<
m=$1 # Bourne Shell has no local command.
shift
Line 4,063 ⟶ 4,574:
done
echo "$m"
}</
=={{header|Ursa}}==
The <code>max</code> function:
<
decl int max i
set max list<0>
Line 4,078 ⟶ 4,589:
return max
end max</
In use: (assuming the function is in the file <code>max.u</code>)
Line 4,095 ⟶ 4,606:
case it is used with <code>fleq</code>, the partial order relation on floating point
numbers.
<
#cast %e
example = fleq$^ <-1.,-2.,0.,5.,4.,6.,1.,-5.></
{{Out}}
<pre>6.000000e+00</pre>
Line 4,105 ⟶ 4,616:
=={{header|V}}==
Assuming it is a list of positive numbers
<
=9</
If it is not
<
=9
=={{header|VBA}}==
<
Sub Main()
Line 4,128 ⟶ 4,639:
Next i
Max_VBA = temp
End Function</
{{Out}}
Line 4,134 ⟶ 4,645:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function greatest_element(arr)
tmp_num = 0
Line 4,148 ⟶ 4,659:
WScript.Echo greatest_element(Array(1,2,3,44,5,6,8))
</syntaxhighlight>
{{Out}}
Line 4,156 ⟶ 4,667:
for numbers (not floats):
<
result: 3
for strings (with configurable ignore-case):
<
" {list}
" {a:1}
if empty(a:list)
endif
let gt_op = a:0>=1 ? get({'i': '>?', 'I': '>#'}, a:1, '>') : '>'
Line 4,172 ⟶ 4,683:
let idx = 1
while idx < len
endwhile
return maxval
endfunction</
=={{header|Visual Basic}}==
<
'return the greatest element in array anArray
'use LBound and UBound to find its length
Line 4,201 ⟶ 4,712:
'print the greatest element
Debug.Print "Greatest element is"; ListMax(b())
End Sub</
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>.
<
if seq
ret winner car.seq
Line 4,217 ⟶ 4,746:
def (max ... args)
(best (>) args)</
<code>(>)</code> is <code>></code> while suppressing infix expansion.
=={{header|WDTE}}==
<
let a => import 'arrays';
Line 4,229 ⟶ 4,758:
-> s.extent 1 >
-> at 0
;</
<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>></code> results in the maximum element.
Line 4,235 ⟶ 4,764:
=={{header|Wortel}}==
The <code>@maxl</code> returns the maximum value of a list:
<
=={{header|Wren}}==
<
var a = [42, 7, -5, 11.7, 58, 22.31, 59, -18]
System.print(max.call(a))</
{{out}}
Line 4,251 ⟶ 4,780:
The set of values is the lengths of the lines of text in the input file.
<
def Tab=$09, LF=$0A, CR=$0D, EOF=$1A;
Line 4,278 ⟶ 4,807:
until C = EOF;
Text(0, "Longest line = "); IntOut(0, Max); CrLf(0);
]</
Example of running the program on its source code:
Line 4,290 ⟶ 4,819:
The desired value is the first in a sequence that has been sorted numerically in descending order.
<
<xsl:output method="text"/>
Line 4,302 ⟶ 4,831:
</xsl:for-each>
</xsl:template>
</xsl:stylesheet></
Sample input:
<
<number>3</number>
<number>1</number>
<number>12</number>
<number>7</number>
</numbers></
{{Out}}
Line 4,319 ⟶ 4,848:
=={{header|Yabasic}}==
<
dim n$(1)
Line 4,331 ⟶ 4,860:
next
print "Alphabetic order: ", m$, ", numeric order: ", m</
=={{header|Yacas}}==
Input:
<
Max({Pi,Exp(1)+2/5,17*Cos(6)/5,Sqrt(91/10)})
Max({1,6,Infinity})
Max({})</
{{Out}}
<pre> 7
Line 4,351 ⟶ 4,880:
> 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}}==
<
(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.14)) //-->3
(6.6).max(T(1,2,3.14)) //-->3.14</
For other object types, you could use:
<
<pre>max(2,1,-40,50,2,4,2) //-->50
max(2) //-->2
Line 4,368 ⟶ 4,910:
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: max
case: 1
Line 4,376 ⟶ 4,918:
input: [1,5,3,2,7]
output: 7
</syntaxhighlight>
=={{header|ZX Spectrum Basic}}==
<
20 LET z=0
30 FOR x=1 TO INT (RND*10)+1
Line 4,386 ⟶ 4,928:
60 LET z=(y AND y>z)+(z AND y<z)
70 NEXT x
80 PRINT '"Max. value = ";z</
|