Return multiple values: Difference between revisions

From Rosetta Code
Content added Content deleted
imported>Tromp
(add BLC solution)
 
(46 intermediate revisions by 24 users not shown)
Line 10: Line 10:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F addsub(x, y)
<syntaxhighlight lang="11l">F addsub(x, y)
R (x + y, x - y)
R (x + y, x - y)


V (summ, difference) = addsub(33, 12)
V (summ, difference) = addsub(33, 12)
print(‘33 + 12 = ’summ)
print(‘33 + 12 = ’summ)
print(‘33 - 12 = ’difference)</lang>
print(‘33 - 12 = ’difference)</syntaxhighlight>


{{out}}
{{out}}
Line 22: Line 22:
33 - 12 = 21
33 - 12 = 21
</pre>
</pre>

=={{header|6502 Assembly}}==
A function can return multiple values by storing them in two or more registers, or in user RAM.
Functions are typically called as a subroutine, e.g. <code>JSR UnpackNibbles</code>.
<syntaxhighlight lang="6502asm">UnpackNibbles:
; Takes accumulator as input.
; Separates a two-digit hex number into its component "nibbles." Left nibble in X, right nibble in Y.

pha ;backup the input.
and #$0F ;chop off the left nibble. What remains is our Y.
tay
pla ;restore input
and #$F0 ;chop off the right nibble. What remains is our X, but it needs to be bit shifted into the right nibble.
lsr
lsr
lsr
lsr
tax ;store in X
rts</syntaxhighlight>

=={{header|68000 Assembly}}==
{{trans|ARM Assembly}}
A function's "return value" is nothing more than the register state upon exit. However, to ensure compatibility between software, there are general calling conventions that compiler-written code will follow that standardizes which registers are used to return values from a function.

This code returns the sum and difference of two integers, which will be passed in via registers D2 and D3.
D2+D3 is returned in D0, D2-D3 is returned in D1.

<syntaxhighlight lang="68000devpac">foo:
MOVE.L D2,D0
MOVE.L D3,D1
ADD.L D1,D0
SUB.L D2,D3
MOVE.L D3,D1
RTS</syntaxhighlight>

=={{header|8086 Assembly}}==
{{trans|ARM Assembly}}
A function's "return value" is nothing more than the register state upon exit. However, to ensure compatibility between software, there are general calling conventions that compiler-written code will follow that standardizes which registers are used to return values from a function.

This function takes two 16-bit numbers in CX and DX, and outputs their sum to AX and their difference to BX.

<syntaxhighlight lang="asm">mov ax,cx
mov bx,dx
add ax,bx
sub cx,dx
mov bx,cx
ret</syntaxhighlight>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>;; To return multiple values:
<syntaxhighlight lang="lisp">;; To return multiple values:
(defun multiple-values (a b)
(defun multiple-values (a b)
(mv a b))
(mv a b))
Line 31: Line 78:
(mv-let (x y)
(mv-let (x y)
(multiple-values 1 2)
(multiple-values 1 2)
(+ x y))</lang>
(+ x y))</syntaxhighlight>
<br><br>
<br><br>

=={{header|Action!}}==
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT

INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!

DEFINE PTR="CARD"
DEFINE RECORD_SIZE="6"
TYPE Record=[CARD min,max,sum]

PROC ArgumentsAsPointers(CARD ARRAY a BYTE n CARD POINTER min,max,sum)
BYTE i

min^=65535 max^=0 sum^=0
FOR i=0 TO n-1
DO
IF a(i)>max^ THEN
max^=a(i)
FI
IF a(i)<min^ THEN
min^=a(i)
FI
sum^==+a(i)
OD
RETURN

PROC ArgumentAsRecord(CARD ARRAY a BYTE n Record POINTER res)
BYTE i

res.min=65535 res.max=0 res.sum=0
FOR i=0 TO n-1
DO
IF a(i)>res.max THEN
res.max=a(i)
FI
IF a(i)<res.min THEN
res.min=a(i)
FI
res.sum==+a(i)
OD
RETURN

PTR FUNC ResultAsRecord(CARD ARRAY a BYTE n)
Record POINTER res
BYTE i

res=Alloc(RECORD_SIZE)
res.min=65535 res.max=0 res.sum=0
FOR i=0 TO n-1
DO
IF a(i)>res.max THEN
res.max=a(i)
FI
IF a(i)<res.min THEN
res.min=a(i)
FI
res.sum==+a(i)
OD
RETURN (res)

PROC Main()
CARD ARRAY a=[123 5267 42 654 234 6531 4432]
CARD minV,maxV,sumV
Record rec
Record POINTER p

Put(125) PutE() ;clear screen
AllocInit(0)

ArgumentsAsPointers(a,7,@minV,@maxV,@sumV)
PrintE("Return multiple values by passing arguments as pointers:")
PrintF("min=%U max=%U sum=%U%E%E",minV,maxV,sumV)

ArgumentAsRecord(a,7,rec)
PrintE("Return multiple values by passing argument as pointer to a record:")
PrintF("min=%U max=%U sum=%U%E%E",rec.min,rec.max,rec.sum)

p=ResultAsRecord(a,7)
PrintE("Return multiple values by returning a pointer to a record:")
PrintF("min=%U max=%U sum=%U%E",p.min,p.max,p.sum)

Free(p,RECORD_SIZE)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Return_multiple_values.png Screenshot from Atari 8-bit computer]
<pre>
Return multiple values by passing arguments as pointers:
min=42 max=6531 sum=17283

Return multiple values by passing argument as pointer to a record:
min=42 max=6531 sum=17283

Return multiple values by returning a pointer to a record:
min=42 max=6531 sum=17283
</pre>


=={{header|Ada}}==
=={{header|Ada}}==
Line 40: Line 184:
a procedure with 'out' parameters.
a procedure with 'out' parameters.
By default, all parameters are 'in', but can also be 'out', 'in out' and 'access'. Writing to an 'out' parameter simply changes the value of the variable passed to the procedure.
By default, all parameters are 'in', but can also be 'out', 'in out' and 'access'. Writing to an 'out' parameter simply changes the value of the variable passed to the procedure.
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure MultiReturn is
procedure MultiReturn is
Line 55: Line 199:
Put_Line ("Diff:" & Integer'Image (thediff));
Put_Line ("Diff:" & Integer'Image (thediff));
end MultiReturn;
end MultiReturn;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 66: Line 210:
<br>
<br>
Tested with Agena 2.9.5 Win32
Tested with Agena 2.9.5 Win32
<lang agena># define a function returning three values
<syntaxhighlight lang="agena"># define a function returning three values
mv := proc() is
mv := proc() is
return 1, 2, "three"
return 1, 2, "three"
Line 74: Line 218:
local a, b, c := mv();
local a, b, c := mv();
print( c, b, a )
print( c, b, a )
epocs</lang>
epocs</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 80: Line 224:
Procedures in Algol 68 can only return one value, so to return multiple values,
Procedures in Algol 68 can only return one value, so to return multiple values,
a structure (or array if all the values have the same mode) can be used.
a structure (or array if all the values have the same mode) can be used.
<lang algol68># example mode for returning multiple values from a procedure #
<syntaxhighlight lang="algol68"># example mode for returning multiple values from a procedure #
MODE PAIR = STRUCT( STRING name, INT value );
MODE PAIR = STRUCT( STRING name, INT value );


Line 98: Line 242:
# access the components separately #
# access the components separately #
print( ( name OF get pair( 1 ), value OF get pair( 2 ), newline ) )
print( ( name OF get pair( 1 ), value OF get pair( 2 ), newline ) )
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 107: Line 251:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
Algol W procedures can't return arrays but records can be used to return multiple values.
Algol W procedures can't return arrays but records can be used to return multiple values.
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% example using a record type to return multiple values from a procedure %
% example using a record type to return multiple values from a procedure %
record Element ( string(2) symbol; integer atomicNumber );
record Element ( string(2) symbol; integer atomicNumber );
Line 134: Line 278:
end
end


end.</lang>
end.</syntaxhighlight>


=={{header|ANSI Standard BASIC}}==
=={{header|Amazing Hopper}}==
Hopper posee una pila de trabajo de alcance global; luego, los datos pueden ser puestos ahí y accedidos desde cualquier parte del programa.
The most straightforward way of returning multiple values is to specify them as parameters.
<syntaxhighlight lang="c">
<lang ANSI Standard BASIC>100 DECLARE EXTERNAL SUB sumdiff
#include <basico.h>
110 !

120 CALL sumdiff(5, 3, sum, diff)
#proto foo(_X_,_Y_)
130 PRINT "Sum is "; sum

140 PRINT "Difference is "; diff
algoritmo
150 END

160 !
_foo(10,1), decimales '13', imprimir
170 EXTERNAL SUB sumdiff(a, b, c, d)

180 LET c = a + b
números(v,w,x,y,z, suma)
190 LET d = a - b
_foo(0.25,0) ---retener(5)--- sumar todo,
200 END SUB</lang>
mover a 'v,w,x,y,z,suma'
imprimir(NL,v,NL, w,NL, x,NL, y,NL, z,NL,NL,suma,NL)

terminar

subrutinas

foo(c,sw)
#(c*10), solo si( sw, NL)
#(c/100), solo si( sw, NL)
#(0.25^c), solo si( sw, convertir a notación; NL)
#(2-(sqrt(c))), solo si( sw, NL)
cuando ' #(!(sw)) '{
#( ((c^c)^c)^c )
}
retornar
</syntaxhighlight>
{{out}}
<pre>
100.0000000000000
0.1000000000000
9.536743e-07
-1.1622776601684

2.5000000000000
0.0025000000000
0.7071067811865
1.5000000000000
0.9785720620877

5.6881788432742
</pre>

=={{header|ARM Assembly}}==
When programming without any rules governing the way you write functions, a function's "return value" is nothing more than the register state upon exit. However, the [https://www.eecs.umich.edu/courses/eecs373/readings/ARM-AAPCS-EABI-v2.08.pdf AAPCS] calling convention dictates that the <code>R0</code> register is used to store a function's return value. (If the return value is larger than 32 bits, the registers <code>R1-R3</code> can also be used.) Following this standard is necessary for human-written assembly code to properly interface with code written by a C compiler.

This function takes two numbers in <code>R0</code> and <code>R1</code>, and returns their sum in <code>R0</code> and their difference in <code>R1</code>.

<syntaxhighlight lang="arm assembly">foo:
MOV R2,R0
MOV R3,R1
ADD R0,R2,R3
SUB R1,R2,R3
BX LR</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>addsub: function [x y]->
<syntaxhighlight lang="rebol">addsub: function [x y]->
@[x+y x-y]
@[x+y x-y]


Line 160: Line 349:


print [a "+" b "=" result\0]
print [a "+" b "=" result\0]
print [a "-" b "=" result\1]</lang>
print [a "-" b "=" result\1]</syntaxhighlight>


{{out}}
{{out}}
Line 169: Line 358:
=={{header|ATS}}==
=={{header|ATS}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<syntaxhighlight lang="ats">//
<lang ATS>//
#include
#include
"share/atspre_staload.hats"
"share/atspre_staload.hats"
Line 188: Line 377:
println! ("33 + 12 = ", sum);
println! ("33 + 12 = ", sum);
println! ("33 - 12 = ", diff);
println! ("33 - 12 = ", diff);
end (* end of [main0] *)</lang>
end (* end of [main0] *)</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
{{works with|AutoHotkey_L}}
Functions may return one value. The conventional way to return multiple values is to bundle them into an Array.
Functions may return one value. The conventional way to return multiple values is to bundle them into an Array.
<lang AutoHotkey>addsub(x, y) {
<syntaxhighlight lang="autohotkey">addsub(x, y) {
return [x + y, x - y]
return [x + y, x - y]
}</lang>
}</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
Return an array.
Return an array.
<syntaxhighlight lang="autoit">
<lang AutoIt>
Func _AddSub($iX, $iY)
Func _AddSub($iX, $iY)
Local $aReturn[2]
Local $aReturn[2]
Line 206: Line 395:
Return $aReturn
Return $aReturn
EndFunc
EndFunc
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|ANSI BASIC}}===
{{works with|Decimal BASIC}}
The most straightforward way of returning multiple values is to specify them as parameters.
<syntaxhighlight lang="basic">100 DECLARE EXTERNAL SUB sumdiff
110 !
120 CALL sumdiff(5, 3, sum, diff)
130 PRINT "Sum is "; sum
140 PRINT "Difference is "; diff
150 END
160 !
170 EXTERNAL SUB sumdiff(a, b, c, d)
180 LET c = a + b
190 LET d = a - b
200 END SUB</syntaxhighlight>
{{out}}
<pre>
Sum is 8
Difference is 2
</pre>

==={{header|BaCon}}===
==={{header|BaCon}}===
BaCon can return homogeneous dynamic arrays, or RECORD data holding heterogeneous types.
BaCon can return homogeneous dynamic arrays, or RECORD data holding heterogeneous types.


<lang freebasic>' Return multiple values
<syntaxhighlight lang="freebasic">' Return multiple values
RECORD multi
RECORD multi
LOCAL num
LOCAL num
Line 230: Line 439:
PRINT rec.num
PRINT rec.num
PRINT rec.s$[0]
PRINT rec.s$[0]
PRINT rec.s$[1]</lang>
PRINT rec.s$[1]</syntaxhighlight>


{{out}}
{{out}}
Line 240: Line 449:
==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
The most straightforward way of returning multiple values is to specify them as RETURNed parameters.
The most straightforward way of returning multiple values is to specify them as RETURNed parameters.
<lang bbcbasic> PROCsumdiff(5, 3, sum, diff)
<syntaxhighlight lang="bbcbasic"> PROCsumdiff(5, 3, sum, diff)
PRINT "Sum is " ; sum
PRINT "Sum is " ; sum
PRINT "Difference is " ; diff
PRINT "Difference is " ; diff
Line 248: Line 457:
c = a + b
c = a + b
d = a - b
d = a - b
ENDPROC</lang>
ENDPROC</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 NUMERIC SUM,DIFF
<syntaxhighlight lang="is-basic">100 NUMERIC SUM,DIFF
110 CALL SUMDIFF(5,3,SUM,DIFF)
110 CALL SUMDIFF(5,3,SUM,DIFF)
120 PRINT "Sum is";SUM:PRINT "Difference is";DIFF
120 PRINT "Sum is";SUM:PRINT "Difference is";DIFF
Line 257: Line 466:
140 DEF SUMDIFF(A,B,REF C,REF D)
140 DEF SUMDIFF(A,B,REF C,REF D)
150 LET C=A+B:LET D=A-B
150 LET C=A+B:LET D=A-B
160 END DEF</lang>
160 END DEF</syntaxhighlight>
==={{header|uBasic/4tH}}===
{{Trans|Forth}}
uBasic/4tH shares many features with Forth - like a stack. Parameters of functions and procedures are passed through this stack, so there is no difference between pushing the values on the stack ''or'' passing them as function parameters. Return values are passed by the stack as well, so if we push additional values ''before'' calling '''RETURN''' we can retrieve them using '''POP()'''.
<syntaxhighlight lang="qbasic">a = FUNC (_MulDiv (33, 11))
b = Pop()

Print "a * b = ";a, "a / b = ";b

Push 33, 11 : Proc _MulDiv
a = Pop() : b = Pop()

Print "a * b = ";a, "a / b = ";b
End

_MulDiv
Param (2)

Push a@ / b@
Return (a@ * b@)</syntaxhighlight>
{{Out}}
<pre>a * b = 363 a / b = 3
a * b = 363 a / b = 3

0 OK, 0:226 </pre>

=={{header|Binary Lambda Calculus}}==
In the lambda calculus, one can return a tuple, which when applied to a function f, applies f to all the tuple elements. For example, <A,B,C> is <code>\f.f A B C</code>. Alternatively, one can use continuation-passing-style (cps), in which the function f is not applied the tuple return value, but instead is passed as an extra initial argument, and then the function can return f applied to the multiple values.

=={{header|BQN}}==
BQN is an array language, and hence arrays are the method of returning multiple values from a function. These values can then be separated with pattern matching.
<syntaxhighlight lang="bqn"> Func←{⟨𝕩+1, 𝕩÷2, 𝕩×3⟩}
(function block)
a‿b‿c←Func 3
⟨ 4 1.5 9 ⟩
a
4
b
1.5
c
9</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
{{trans|Haskell}}
{{trans|Haskell}}
Every function returns one value. The conventional way to return multiple values is to return a tuple.
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<lang bracmat>(addsub=x y.!arg:(?x.?y)&(!x+!y.!x+-1*!y));</lang>
<syntaxhighlight lang="bracmat">(addsub=x y.!arg:(?x.?y)&(!x+!y.!x+-1*!y));</syntaxhighlight>
You can use pattern matching to extract the components:
You can use pattern matching to extract the components:
<lang bracmat>( addsub$(33.12):(?sum.?difference)
<syntaxhighlight lang="bracmat">( addsub$(33.12):(?sum.?difference)
& out$("33 + 12 = " !sum)
& out$("33 + 12 = " !sum)
& out$("33 - 12 = " !difference)
& out$("33 - 12 = " !difference)
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>33 + 12 = 45
<pre>33 + 12 = 45
Line 274: Line 523:
=={{header|C}}==
=={{header|C}}==
C has structures which can hold multiple data elements of varying types.
C has structures which can hold multiple data elements of varying types.
<lang c>#include<stdio.h>
<syntaxhighlight lang="c">#include<stdio.h>


typedef struct{
typedef struct{
Line 298: Line 547:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 305: Line 554:


C99 and above also allow structure literals to refer to the name, rather than position, of the element to be initialized:
C99 and above also allow structure literals to refer to the name, rather than position, of the element to be initialized:
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


typedef struct {
typedef struct {
Line 322: Line 571:
printf("The name's %s. %s %s.\n", me.last, me.first, me.last);
printf("The name's %s. %s %s.\n", me.last, me.first, me.last);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>The name's Bond. James Bond.
<pre>The name's Bond. James Bond.
Line 328: Line 577:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
The preferred way to return multiple values in C# is to use "out" paremeters on the method. This can be in addition to the value returned by the method.
The preferred way to return multiple values in C# is to use "out" parameters on the method. This can be in addition to the value returned by the method.
<lang c sharp>using System;
<syntaxhighlight lang="c sharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 350: Line 599:
min = sortedNums.First();
min = sortedNums.First();
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Min: -3
<pre>Min: -3
Line 357: Line 606:
=={{header|C++}}==
=={{header|C++}}==
Since C++11, the C++-standard-library includes tuples, as well as an easy way to destructure them.
Since C++11, the C++-standard-library includes tuples, as well as an easy way to destructure them.
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <array>
#include <array>
#include <cstdint>
#include <cstdint>
Line 375: Line 624:
std::tie(min, max) = minmax(numbers.data(), numbers.size());
std::tie(min, max) = minmax(numbers.data(), numbers.size());
std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<PRE>The smallest number is -10, the biggest 987!</PRE>
<PRE>The smallest number is -10, the biggest 987!</PRE>
Line 382: Line 631:
Every function returns one value.
Every function returns one value.
The conventional way to return multiple values is to bundle them into an array.
The conventional way to return multiple values is to bundle them into an array.
<lang Clipper>Function Addsub( x, y )
<syntaxhighlight lang="clipper">Function Addsub( x, y )
Return { x+y, x-y }</lang>
Return { x+y, x-y }</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
Multiple values can be returned by packaging them in a vector.
Multiple values can be returned by packaging them in a vector.
At receiving side, these arguments can be obtained individually by using [http://blog.jayfields.com/2010/07/clojure-destructuring.html destructuring].
At receiving side, these arguments can be obtained individually by using [http://blog.jayfields.com/2010/07/clojure-destructuring.html destructuring].
<lang clojure>(defn quot-rem [m n] [(quot m n) (rem m n)])
<syntaxhighlight lang="clojure">(defn quot-rem [m n] [(quot m n) (rem m n)])


; The following prints 3 2.
; The following prints 3 2.
(let [[q r] (quot-rem 11 3)]
(let [[q r] (quot-rem 11 3)]
(println q)
(println q)
(println r))</lang>
(println r))</syntaxhighlight>
In complex cases, it would make more sense to return a map, which can be destructed in a similar manner.
In complex cases, it would make more sense to return a map, which can be destructed in a similar manner.
<lang clojure>(defn quot-rem [m n]
<syntaxhighlight lang="clojure">(defn quot-rem [m n]
{:q (quot m n)
{:q (quot m n)
:r (rem m n)})
:r (rem m n)})
Line 402: Line 651:
(let [{:keys [q r]} (quot-rem 11 3)]
(let [{:keys [q r]} (quot-rem 11 3)]
(println q)
(println q)
(println r))</lang>
(println r))</syntaxhighlight>


=={{header|CLU}}==
<syntaxhighlight lang="clu">% Returning multiple values (along with type parameterization)
% was actually invented with CLU.

% Do note that the procedure is actually returning multiple
% values; it's not returning a tuple and unpacking it.
% That doesn't exist in CLU.

% For added CLU-ness, this function is fully general, requiring
% only that its arguments support addition and subtraction in any way

add_sub = proc [T,U,V,W: type] (a: T, b: U) returns (V, W)
signals (overflow)
where T has add: proctype (T,U) returns (V) signals (overflow),
sub: proctype (T,U) returns (W) signals (overflow)
return (a+b, a-b) resignal overflow
end add_sub


% And actually using it
start_up = proc ()
add_sub_int = add_sub[int,int,int,int] % boring, but does what you'd expect
po: stream := stream$primary_output()
% returning two values from the function
sum, diff: int := add_sub_int(33, 12)

% print out both
stream$putl(po, "33 + 12 = " || int$unparse(sum))
stream$putl(po, "33 - 12 = " || int$unparse(diff))
end start_up</syntaxhighlight>
{{out}}
<pre>33 + 12 = 45
33 - 12 = 21</pre>
=={{header|CMake}}==
=={{header|CMake}}==
<lang cmake># Returns the first and last characters of string.
<syntaxhighlight lang="cmake"># Returns the first and last characters of string.
function(firstlast string first last)
function(firstlast string first last)
# f = first character.
# f = first character.
Line 421: Line 704:


firstlast("Rosetta Code" begin end)
firstlast("Rosetta Code" begin end)
message(STATUS "begins with ${begin}, ends with ${end}")</lang>
message(STATUS "begins with ${begin}, ends with ${end}")</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 436: Line 719:
{{works with|GnuCOBOL}}
{{works with|GnuCOBOL}}


<syntaxhighlight lang="cobol">
<lang COBOL>
identification division.
identification division.
program-id. multiple-values.
program-id. multiple-values.
Line 510: Line 793:
goback.
goback.
end function multiples.
end function multiples.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 524: Line 807:


Returning a single value is accomplished by evaluating an expression (which itself yields a single value) at the end of a body of forms.
Returning a single value is accomplished by evaluating an expression (which itself yields a single value) at the end of a body of forms.
<lang lisp>(defun return-three ()
<syntaxhighlight lang="lisp">(defun return-three ()
3)</lang>
3)</syntaxhighlight>
The next possibility is that of returning no values at all. For this, the <code>values</code> function is used, with no arguments:
The next possibility is that of returning no values at all. For this, the <code>values</code> function is used, with no arguments:
<lang lisp>(defun return-nothing ()
<syntaxhighlight lang="lisp">(defun return-nothing ()
(values))</lang>
(values))</syntaxhighlight>
To combine the values of multiple expressions into a multi-value return, <code>values</code> is used with arguments. The following is from an interactive [[CLISP]] session. CLISP's listener shows multiple values separated by a semicolon:
To combine the values of multiple expressions into a multi-value return, <code>values</code> is used with arguments. The following is from an interactive [[CLISP]] session. CLISP's listener shows multiple values separated by a semicolon:
<lang lisp>[1]> (defun add-sub (x y) (values-list (list (+ x y) (- x y))))
<syntaxhighlight lang="lisp">[1]> (defun add-sub (x y) (values-list (list (+ x y) (- x y))))
ADD-SUB
ADD-SUB
[2]> (add-sub 4 2) ; 6 (primary) and 2
[2]> (add-sub 4 2) ; 6 (primary) and 2
Line 541: Line 824:
10
10
[5]> (multiple-value-call #'+ (add-sub 4 2) (add-sub 3 1)) ; 6+2+4+2
[5]> (multiple-value-call #'+ (add-sub 4 2) (add-sub 3 1)) ; 6+2+4+2
14</lang>
14</syntaxhighlight>
What happens if something tries to use the value of a form which returned <code>(values)</code>? In this case the behavior defaults to taking the value <code>nil</code>:
What happens if something tries to use the value of a form which returned <code>(values)</code>? In this case the behavior defaults to taking the value <code>nil</code>:
<lang lisp>(car (values)) ;; no error: same as (car nil)</lang>
<syntaxhighlight lang="lisp">(car (values)) ;; no error: same as (car nil)</syntaxhighlight>
What if the <code>values</code> function is applied to some expressions which also yield multiple values, or which do not yield any values? The answer is that only the primary value is taken from each expression, or the value <code>nil</code> for any expression which did not yield a value:
What if the <code>values</code> function is applied to some expressions which also yield multiple values, or which do not yield any values? The answer is that only the primary value is taken from each expression, or the value <code>nil</code> for any expression which did not yield a value:
<lang lisp>(values (values 1 2 3) (values) 'a)</lang>
<syntaxhighlight lang="lisp">(values (values 1 2 3) (values) 'a)</syntaxhighlight>
yields three values:
yields three values:
<pre>-> 1; NIL; A</pre>
<pre>-> 1; NIL; A</pre>
This also means that <code>values</code> can be used to reduce a multiple value to a single value:
This also means that <code>values</code> can be used to reduce a multiple value to a single value:
<lang lisp>;; return exactly one value, no matter how many expr returns,
<syntaxhighlight lang="lisp">;; return exactly one value, no matter how many expr returns,
;; nil if expr returns no values
;; nil if expr returns no values
(values expr)</lang>
(values expr)</syntaxhighlight>
Multiple values are extracted in several ways.
Multiple values are extracted in several ways.


1. Binding to variables:
1. Binding to variables:
<lang lisp>(multiple-value-bind (dividend remainder) (truncate 16 3)
<syntaxhighlight lang="lisp">(multiple-value-bind (dividend remainder) (truncate 16 3)
;; in this scope dividend is 5; remainder is 1
;; in this scope dividend is 5; remainder is 1
)</lang>
)</syntaxhighlight>


2. Conversion to a list:
2. Conversion to a list:
<lang lisp>(multiple-value-list (truncate 16 3)) ;; yields (5 1)</lang>
<syntaxhighlight lang="lisp">(multiple-value-list (truncate 16 3)) ;; yields (5 1)</syntaxhighlight>


3. Reification of multiple values as arguments to another function:
3. Reification of multiple values as arguments to another function:
<lang lisp>;; pass arguments 5 1 to +, resulting in 6:
<syntaxhighlight lang="lisp">;; pass arguments 5 1 to +, resulting in 6:
(multiple-value-call #'+ (truncate 16 3))</lang>
(multiple-value-call #'+ (truncate 16 3))</syntaxhighlight>


4. Assignment to variables:
4. Assignment to variables:
<lang lisp>;; assign 5 to dividend, 1 to remainder:
<syntaxhighlight lang="lisp">;; assign 5 to dividend, 1 to remainder:
(multiple-value-setq (dividend remainder) (truncate 16 1))</lang>
(multiple-value-setq (dividend remainder) (truncate 16 1))</syntaxhighlight>
<code>(values ...)</code> syntax is treated as a multiple value place by <code>setf</code> and other operators, allowing the above to be expressed this way:
<code>(values ...)</code> syntax is treated as a multiple value place by <code>setf</code> and other operators, allowing the above to be expressed this way:
<lang lisp>(setf (values dividend remainder) (truncate 16 1))</lang>
<syntaxhighlight lang="lisp">(setf (values dividend remainder) (truncate 16 1))</syntaxhighlight>


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


# In Cowgol, subroutines can simply define multiple output parameters.
# In Cowgol, subroutines can simply define multiple output parameters.
Line 599: Line 882:


print("Min: "); print_i8(least); print_nl();
print("Min: "); print_i8(least); print_nl();
print("Max: "); print_i8(most); print_nl();</lang>
print("Max: "); print_i8(most); print_nl();</syntaxhighlight>


{{out}}
{{out}}
Line 607: Line 890:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.typecons, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.typecons, std.algorithm;




Line 634: Line 917:


writefln("33 + 12 = %d\n33 - 12 = %d", a, b);
writefln("33 + 12 = %d\n33 - 12 = %d", a, b);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>33 + 12 = 45
<pre>33 + 12 = 45
Line 641: Line 924:
=={{header|Dc}}==
=={{header|Dc}}==
Define a divmod macro <code>~</code> which takes <code>a b</code> on the stack and returns <code>a/b a%b</code>.
Define a divmod macro <code>~</code> which takes <code>a b</code> on the stack and returns <code>a/b a%b</code>.
<lang dc>[ S1 S2 l2 l1 / L2 L1 % ] s~
<syntaxhighlight lang="dc">[ S1 S2 l2 l1 / L2 L1 % ] s~
1337 42 l~ x f</lang>
1337 42 l~ x f</syntaxhighlight>
{{out}}
{{out}}
<pre>35
<pre>35
Line 649: Line 932:
=={{header|Delphi}}/{{header|Pascal}}==
=={{header|Delphi}}/{{header|Pascal}}==
Delphi functions return a single value, but var parameters of a function or procedure can be modified and act as return values.
Delphi functions return a single value, but var parameters of a function or procedure can be modified and act as return values.
<lang Delphi>program ReturnMultipleValues;
<syntaxhighlight lang="delphi">program ReturnMultipleValues;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 665: Line 948:
Writeln(x);
Writeln(x);
Writeln(y);
Writeln(y);
end.</lang>
end.</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
Line 671: Line 954:
A typical way to return multiple values in Dyalect is to use tuples:
A typical way to return multiple values in Dyalect is to use tuples:


<lang Dyalect>func divRem(x, y) {
<syntaxhighlight lang="dyalect">func divRem(x, y) {
(x / y, x % y)
(x / y, x % y)
}</lang>
}</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>function-returning-multiple-values:
<syntaxhighlight lang="dejavu">function-returning-multiple-values:
10 20
10 20


!print !print function-returning-multiple-values
!print !print function-returning-multiple-values
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>10
<pre>10
20</pre>
20</pre>

=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
proc addSubtract a b . sum diff .
sum = a + b
diff = a - b
.
addSubtract 7 5 sum diff
print "Sum: " & sum
print "Difference: " & diff
</syntaxhighlight>
{{out}}
<pre>
Sum: 12
Difference: 2
</pre>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
One can return the result of the '''values''' function, or a list.
One can return the result of the '''values''' function, or a list.
<lang scheme>
<syntaxhighlight lang="scheme">
(define (plus-minus x y)
(define (plus-minus x y)
(values (+ x y) (- x y)))
(values (+ x y) (- x y)))
Line 698: Line 997:
(plus-minus 3 4)
(plus-minus 3 4)
→ (7 -1)
→ (7 -1)
</syntaxhighlight>
</lang>


=={{header|ECL}}==
=={{header|ECL}}==
<lang>MyFunc(INTEGER i1,INTEGER i2) := FUNCTION
<syntaxhighlight lang="text">MyFunc(INTEGER i1,INTEGER i2) := FUNCTION
RetMod := MODULE
RetMod := MODULE
EXPORT INTEGER Add := i1 + i2;
EXPORT INTEGER Add := i1 + i2;
Line 712: Line 1,011:
MyFunc(3,4).Add;
MyFunc(3,4).Add;
MyFunc(3,4).Prod;
MyFunc(3,4).Prod;
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
Every function returns one value. Multiple values can be returned in a tuple.
Every function returns one value. Multiple values can be returned in a tuple.
<lang Eiffel>some_feature: TUPLE
<syntaxhighlight lang="eiffel">some_feature: TUPLE
do
do
Result := [1, 'j', "r"]
Result := [1, 'j', "r"]
end</lang>
end</syntaxhighlight>
Greater control over the type of return values can also be enforced by explicitly declaring the type of the generic parameters.
Greater control over the type of return values can also be enforced by explicitly declaring the type of the generic parameters.
<lang Eiffel>some_feature: TUPLE[INTEGER_32, CHARACTER_8, STRING_8]
<syntaxhighlight lang="eiffel">some_feature: TUPLE[INTEGER_32, CHARACTER_8, STRING_8]
do
do
--Result := [ ] -- compile error
--Result := [ ] -- compile error
Line 727: Line 1,026:
Result := [1, 'j', "r"] -- okay
Result := [1, 'j', "r"] -- okay
Result := [1, 'j', "r", 1.23] -- also okay
Result := [1, 'j', "r", 1.23] -- also okay
end</lang>
end</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 6.x :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
Line 752: Line 1,051:
console.printLine("Min: ",min," Max: ",max)
console.printLine("Min: ",min," Max: ",max)
}</lang>
}</syntaxhighlight>
=== Using Tuples syntax ===
<syntaxhighlight lang="elena">import system'routines;
import extensions;
extension op
{
::(int, int) MinMax()
{
var ordered := self.ascendant();
^ (ordered.FirstMember, ordered.LastMember);
}
}
public program()
{
var values := new int[]{4, 51, 1, -3, 3, 6, 8, 26, 2, 4};
(int min, int max) := values.MinMax();
console.printLine("Min: ",min," Max: ",max)
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 760: Line 1,081:
=={{header|Elixir}}==
=={{header|Elixir}}==
Elixir returns in the tuple form when returning more than one value.
Elixir returns in the tuple form when returning more than one value.
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def addsub(a, b) do
def addsub(a, b) do
{a+b, a-b}
{a+b, a-b}
Line 767: Line 1,088:


{add, sub} = RC.addsub(7, 4)
{add, sub} = RC.addsub(7, 4)
IO.puts "Add: #{add},\tSub: #{sub}"</lang>
IO.puts "Add: #{add},\tSub: #{sub}"</syntaxhighlight>


{{out}}
{{out}}
Line 775: Line 1,096:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>% Put this code in return_multi.erl and run it as "escript return_multi.erl"
<syntaxhighlight lang="erlang">% Put this code in return_multi.erl and run it as "escript return_multi.erl"


-module(return_multi).
-module(return_multi).
Line 785: Line 1,106:
multiply(A, B) ->
multiply(A, B) ->
{A * B, A + B, A - B}.
{A * B, A + B, A - B}.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>12 7 -1
<pre>12 7 -1
Line 792: Line 1,113:
=={{header|ERRE}}==
=={{header|ERRE}}==
FUNCTIONs in ERRE language return always a single value, but PROCEDUREs can return multiple values defining a parameter output list in procedure declaration using '->' separator.
FUNCTIONs in ERRE language return always a single value, but PROCEDUREs can return multiple values defining a parameter output list in procedure declaration using '->' separator.
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM RETURN_VALUES
PROGRAM RETURN_VALUES


Line 805: Line 1,126:
PRINT("Difference is";DIFF)
PRINT("Difference is";DIFF)
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>

=={{header|Euler}}==
Euler procedures can return a list (Euler's only data structure), this is used here to return three values from the getMV procedure.
<br>
Procedures are defined by enclosing their text between ` and '. They can then be assigned to a variable for later use.
<br>
Lists are constructed by placing the values between ( and ). Once assigned to a variable, the list can be subscripted to access the individual elements (which can themselves be lists).
'''begin'''
'''new''' mv; '''new''' getMV;
getMV &lt;- ` '''formal''' v; ( v, v * v, v * v * v ) &apos;;
mv &lt;- getMV( 3 );
'''out''' mv[ 1 ];
'''out''' mv[ 2 ];
'''out''' mv[ 3 ]
'''end''' $


=={{header|Euphoria}}==
=={{header|Euphoria}}==
Any Euphoria object can be returned. A sequence of objects can be returned, made from multiple data types as in this example.
Any Euphoria object can be returned. A sequence of objects can be returned, made from multiple data types as in this example.
<lang euphoria>include std\console.e --only for any_key, to help make running this program easy on windows GUI
<syntaxhighlight lang="euphoria">include std\console.e --only for any_key, to help make running this program easy on windows GUI


integer aWholeNumber = 1
integer aWholeNumber = 1
Line 822: Line 1,161:
result = addmultret(aWholeNumber, aFloat, aSequence) --call function, assign what it gets into result - {9.999999, 23.999988}
result = addmultret(aWholeNumber, aFloat, aSequence) --call function, assign what it gets into result - {9.999999, 23.999988}
? result
? result
any_key()</lang>
any_key()</syntaxhighlight>


{{out}}
{{out}}
Line 831: Line 1,170:
A function always returns exactly one value.
A function always returns exactly one value.
To return multiple results, they are typically packed into a tuple:
To return multiple results, they are typically packed into a tuple:
<lang fsharp>let addSub x y = x + y, x - y
<syntaxhighlight lang="fsharp">let addSub x y = x + y, x - y


let sum, diff = addSub 33 12
let sum, diff = addSub 33 12
printfn "33 + 12 = %d" sum
printfn "33 + 12 = %d" sum
printfn "33 - 12 = %d" diff</lang>
printfn "33 - 12 = %d" diff</syntaxhighlight>


Output parameters from .NET APIs are automatically converted to tuples by the compiler.
Output parameters from .NET APIs are automatically converted to tuples by the compiler.
Line 843: Line 1,182:
With stack-oriented languages like Factor, a function returns multiple values by pushing them on the data stack.
With stack-oriented languages like Factor, a function returns multiple values by pushing them on the data stack.
For example, this word ''*/'' pushes both x*y and x/y.
For example, this word ''*/'' pushes both x*y and x/y.
<lang factor>USING: io kernel math prettyprint ;
<syntaxhighlight lang="factor">USING: io kernel math prettyprint ;
IN: script
IN: script


Line 852: Line 1,191:


[ "15 * 3 = " write . ]
[ "15 * 3 = " write . ]
[ "15 / 3 = " write . ] bi*</lang>
[ "15 / 3 = " write . ] bi*</syntaxhighlight>
Its stack effect declares that ''*/'' always returns 2 values. To return a variable number of values, a word must bundle those values into a [[sequence]] (perhaps an array or vector). For example, ''factors'' (defined in ''math.primes.factors'' and demonstrated at [[Prime decomposition#Factor]]) returns a sequence of prime factors.
Its stack effect declares that ''*/'' always returns 2 values. To return a variable number of values, a word must bundle those values into a [[sequence]] (perhaps an array or vector). For example, ''factors'' (defined in ''math.primes.factors'' and demonstrated at [[Prime decomposition#Factor]]) returns a sequence of prime factors.


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>[\$@$@*@@/]f: { in: a b, out: a*b a/b }
<syntaxhighlight lang="false">[\$@$@*@@/]f: { in: a b, out: a*b a/b }
6 2f;! .` ,. { 3 12 }</lang>
6 2f;! .' ,. { 3 12 }</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
It is natural to return multiple values on the parameter stack. Many built-in operators and functions do so as well ('''/mod''', '''open-file''', etc.).
It is natural to return multiple values on the parameter stack. Many built-in operators and functions do so as well ('''/mod''', '''open-file''', etc.).
<lang forth>: muldiv ( a b -- a*b a/b )
<syntaxhighlight lang="forth">: muldiv ( a b -- a*b a/b )
2dup / >r * r> ;</lang>
2dup / >r * r> ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{trans|Haskell}}
{{trans|Haskell}}
<lang Fortran>module multiple_values
<syntaxhighlight lang="fortran">module multiple_values
implicit none
implicit none
type res
type res
Line 886: Line 1,225:
print *, addsub(33, 22)
print *, addsub(33, 22)
end program
end program
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


' One way to return multiple values is to use ByRef parameters for the additional one(s)
' One way to return multiple values is to use ByRef parameters for the additional one(s)
Line 941: Line 1,280:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 954: Line 1,293:
=={{header|Frink}}==
=={{header|Frink}}==
The most common way of returning multiple values from a function is to return them as an array, which can be disassembled and set into individual variables on return.
The most common way of returning multiple values from a function is to return them as an array, which can be disassembled and set into individual variables on return.
<lang frink>
<syntaxhighlight lang="frink">
divMod[a, b] := [a div b, a mod b]
divMod[a, b] := [a div b, a mod b]


[num, remainder] = divMod[10, 3]
[num, remainder] = divMod[10, 3]
</syntaxhighlight>
</lang>


=={{header|FunL}}==
=={{header|FunL}}==
{{trans|Scala}}
{{trans|Scala}}
<lang funl>def addsub( x, y ) = (x + y, x - y)
<syntaxhighlight lang="funl">def addsub( x, y ) = (x + y, x - y)


val (sum, difference) = addsub( 33, 12 )
val (sum, difference) = addsub( 33, 12 )


println( sum, difference, addsub(33, 12) )</lang>
println( sum, difference, addsub(33, 12) )</syntaxhighlight>


{{out}}
{{out}}
Line 978: Line 1,317:


Here is an example of returning multiple values using pointers:
Here is an example of returning multiple values using pointers:
<lang futurebasic>
<syntaxhighlight lang="futurebasic">
include "ConsoleWindow"

local fn ReturnMultipleValues( strIn as Str255, strOut as ^Str255, letterCount as ^long )
local fn ReturnMultipleValues( strIn as Str255, strOut as ^Str255, letterCount as ^long )
dim as Str255 s
Str255 s

// Test if incoming string is empty, and exit function if it is
// Test if incoming string is empty, and exit function if it is
if strIn[0] == 0 then exit fn
if strIn[0] == 0 then exit fn

// Prepend this string to incoming string and return it
// Prepend this string to incoming string and return it
s = "Here is your original string: "
s = "Here is your original string: "
strOut.nil$ = s + strIn
strOut.nil$ = s + strIn

// Get length of combined string and return it
// Get length of combined string and return it
// Note: In FutureBasic string[0] is interchangeable with Len(string)
// Note: In FutureBasic string[0] is interchangeable with Len(string)
letterCount.nil& = strIn[0] + s[0]
letterCount.nil& = strIn[0] + s[0]
end fn
end fn


dim as Str255 outStr
Str255 outStr
dim as long outCount
long outCount


fn ReturnMultipleValues( "Hello, World!", @outStr, @outCount )
fn ReturnMultipleValues( "Hello, World!", @outStr, @outCount )
print outStr; ". The combined strings have"; outCount; " letters in them."
print outStr; ". The combined strings have ";outCount; " letters in them."

</lang>
HandleEvents
</syntaxhighlight>


Output:
Output:
Line 1,009: Line 1,348:


Another way to pass multiple values from a function is with records (AKA structures):
Another way to pass multiple values from a function is with records (AKA structures):
<lang>
<syntaxhighlight lang="text">
include "ConsoleWindow"

// Elements in global array
// Elements in global array
_maxDim = 3
_maxDim = 3


begin record Addresses
begin record Addresses
dim as Str63 name
Str63 name
dim as Str15 phone
Str15 phone
dim as long zip
long zip
end record
end record


begin globals
begin globals
dim as Addresses gAddressData(_maxDim)
Addresses gAddressData(_maxDim)
end globals
end globals


local fn FillRecord( array(_maxDim) as Addresses )
local fn FillRecord( array(_maxDim) as Addresses )
array.name(0) = "John Doe"
array.name(0) = "John Doe"
array.name(1) = "Mary Jones"
array.name(1) = "Mary Jones"
array.name(2) = "Bill Smith
array.name(2) = "Bill Smith"

array.phone(0) = "555-359-4411"
array.phone(0) = "555-359-4411"
array.phone(1) = "555-111-2211"
array.phone(1) = "555-111-2211"
array.phone(2) = "555-769-8071"
array.phone(2) = "555-769-8071"

array.zip(0) = 12543
array.zip(0) = 12543
array.zip(1) = 67891
array.zip(1) = 67891
array.zip(2) = 54321
array.zip(2) = 54321
end fn
end fn


Line 1,042: Line 1,379:
fn FillRecord( gAddressData(0) )
fn FillRecord( gAddressData(0) )


dim as short i
short i

for i = 0 to 2
for i = 0 to 2
print gAddressData.name(i); ", ";
print gAddressData.name(i); ", ";
print gAddressData.phone(i); ", Zip:";
print gAddressData.phone(i); ", Zip:";
print gAddressData.zip(i)
print gAddressData.zip(i)
next
next

</lang>
HandleEvents
</syntaxhighlight>


Output:
Output:
Line 1,059: Line 1,397:


You can also use global arrays to return multiple values from a function as in this example:
You can also use global arrays to return multiple values from a function as in this example:
<lang>
<syntaxhighlight lang="text">
include "ConsoleWindow"

// Elements in global array
// Elements in global array
_maxDim = 3
_maxDim = 3


begin globals
begin globals
dim as Str31 gAddressArray(_maxDim, _maxDim)
Str31 gAddressArray(_maxDim, _maxDim)
end globals
end globals


Line 1,072: Line 1,408:
array( 0, 0 ) = "John Doe"
array( 0, 0 ) = "John Doe"
array( 1, 0 ) = "Mary Jones"
array( 1, 0 ) = "Mary Jones"
array( 2, 0 ) = "Bill Smith
array( 2, 0 ) = "Bill Smith"


array( 0, 1 ) = "555-359-4411"
array( 0, 1 ) = "555-359-4411"
Line 1,086: Line 1,422:
fn FillRecord( gAddressArray( 0, 0 ) )
fn FillRecord( gAddressArray( 0, 0 ) )


dim as short i, j
short i, j


for i = 0 to 2
for i = 0 to 2
j = 0
j = 0
print gAddressArray(i, j ); ", ";
print gAddressArray(i, j ); ", ";
print gAddressArray(i, j + 1); ", Zip: ";
print gAddressArray(i, j + 1); ", Zip: ";
print gAddressArray(i, j + 1)
print gAddressArray(i, j + 1)
next
next

</lang>
HandleEvents
</syntaxhighlight>


Output:
Output:
Line 1,104: Line 1,442:


Here is another example using FB's containers -- bit buckets that can hold up to 2GB of data contingent on system memory.
Here is another example using FB's containers -- bit buckets that can hold up to 2GB of data contingent on system memory.
<lang>
<syntaxhighlight lang="text">
include "ConsoleWindow"

begin globals
begin globals
// An FB container can hold up to 2GB of data, contingent on system memory
// An FB container can hold up to 2GB of data, contingent on system memory
dim as container gC1, gC2
container gC1, gC2
end globals
end globals


Line 1,151: Line 1,487:
// Check the new results
// Check the new results
print gC1 : print gC2
print gC1 : print gC2

</lang>
HandleEvents
</syntaxhighlight>


Output:
Output:
Line 1,176: Line 1,514:
=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==


{{FormulaeEntry|page=https://formulae.org/?script=examples/Return_multiple_values}}
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'''

Every function returns one value. The conventional way to return multiple values is to return a list.

In the following example, the function returns the sum and product of two given numbers.

[[File:Fōrmulæ - Return multiple values 01.png]]


[[File:Fōrmulæ - Return multiple values 02.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æ - Return multiple values 03.png]]
In '''[https://formulae.org/?example=Return_multiple_values this]''' page you can see the program(s) related to this task and their results.


=={{header|Go}}==
=={{header|Go}}==
Functions can return multiple values in Go:
Functions can return multiple values in Go:
<lang go>func addsub(x, y int) (int, int) {
<syntaxhighlight lang="go">func addsub(x, y int) (int, int) {
return x + y, x - y
return x + y, x - y
}</lang>
}</syntaxhighlight>
Or equivalently using named return style:
Or equivalently using named return style:
<lang go>func addsub(x, y int) (sum, difference int) {
<syntaxhighlight lang="go">func addsub(x, y int) (sum, difference int) {
sum = x + y
sum = x + y
difference = x - y
difference = x - y
return
return
}</lang>
}</syntaxhighlight>
When a function returns multiple values, you must assign to a comma-separated list of targets:
When a function returns multiple values, you must assign to a comma-separated list of targets:
<lang go>sum, difference := addsub(33, 12)
<syntaxhighlight lang="go">sum, difference := addsub(33, 12)
fmt.Printf("33 + 12 = %d\n", sum)
fmt.Printf("33 + 12 = %d\n", sum)
fmt.Printf("33 - 12 = %d\n", difference)</lang>
fmt.Printf("33 - 12 = %d\n", difference)</syntaxhighlight>
::<lang go>package main
::<syntaxhighlight lang="go">package main


import (
import (
Line 1,260: Line 1,606:
puss, poo := myCat.Puss()
puss, poo := myCat.Puss()
fmt.Println(puss, poo) // prt Kitty Cat
fmt.Println(puss, poo) // prt Kitty Cat
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
In Groovy functions return one value. One way to return multiple ones is to use anonymous maps as a sort of tuple.
In Groovy functions return one value. One way to return multiple ones is to use anonymous maps as a sort of tuple.
<lang groovy>def addSub(x,y) {
<syntaxhighlight lang="groovy">def addSub(x,y) {
[
[
sum: x+y,
sum: x+y,
difference: x-y
difference: x-y
]
]
}</lang>
}</syntaxhighlight>
Result:
Result:
<lang groovy>addSub(10,12)
<syntaxhighlight lang="groovy">addSub(10,12)
["sum":22, "difference":-2]</lang>
["sum":22, "difference":-2]</syntaxhighlight>


And although Groovy functions only return one value, Groovy ''assignments'' of Iterable objects (lists, arrays, sets, etc.) can be distributed across multiple ''variables'', like this:
And although Groovy functions only return one value, Groovy ''assignments'' of Iterable objects (lists, arrays, sets, etc.) can be distributed across multiple ''variables'', like this:


<lang groovy>def addSub2(x,y) {
<syntaxhighlight lang="groovy">def addSub2(x,y) {
[ x+y , x-y ]
[ x+y , x-y ]
}
}
Line 1,283: Line 1,629:
def (sum, diff) = addSub2(50, 5)
def (sum, diff) = addSub2(50, 5)
assert sum == 55
assert sum == 55
assert diff == 45</lang>
assert diff == 45</syntaxhighlight>


If there are fewer elements than variables, the leftover variables are assigned null. If there are more elements than variables, the last variable is assigned the collected remainder of the elements.
If there are fewer elements than variables, the leftover variables are assigned null. If there are more elements than variables, the last variable is assigned the collected remainder of the elements.
Line 1,289: Line 1,635:
=={{header|Harbour}}==
=={{header|Harbour}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into an array.
Every function returns one value. The conventional way to return multiple values is to bundle them into an array.
<lang visualfoxpro>FUNCTION Addsub( x, y )
<syntaxhighlight lang="visualfoxpro">FUNCTION Addsub( x, y )
RETURN { x + y, x - y }</lang>
RETURN { x + y, x - y }</syntaxhighlight>
However, we can 'return' multiple individual values, that are produced/processed/altered inside a function, indirectly, passing parameters `by reference`.

For example:
<syntaxhighlight lang="visualfoxpro">
PROCEDURE Main()
LOCAL Street, City, Country
IF GetAddress( @Street, @City, @Country )
? hb_StrFormat( "Adrress: %s, %s, %s", Street, City, Country )
// output: Route 42, Android-Free Town, FOSSLAND
ELSE
? "Cannot obtain address!"
ENDIF
FUNCTION GetAddress( cS, cC, cCn)
cS := "Route 42"
cC := "Android-Free Town"
cCn:= "FOSSLAND"
RETURN .T.
</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<lang haskell> addsub x y = (x + y, x - y)</lang>
<syntaxhighlight lang="haskell"> addsub x y = (x + y, x - y)</syntaxhighlight>
You can use pattern matching to extract the components:
You can use pattern matching to extract the components:
<lang haskell>main = do
<syntaxhighlight lang="haskell">main = do
let (sum, difference) = addsub 33 12
let (sum, difference) = addsub 33 12
putStrLn ("33 + 12 = " ++ show sum)
putStrLn ("33 + 12 = " ++ show sum)
putStrLn ("33 - 12 = " ++ show difference)</lang>
putStrLn ("33 - 12 = " ++ show difference)</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 1,305: Line 1,671:


The following examples return 1, 2, 3 in different ways:
The following examples return 1, 2, 3 in different ways:
<lang Icon>procedure retList() # returns as ordered list
<syntaxhighlight lang="icon">procedure retList() # returns as ordered list
return [1,2,3]
return [1,2,3]
end
end
Line 1,330: Line 1,696:
procedure retRecord() # return as a record, least general method
procedure retRecord() # return as a record, least general method
return retdata(1,2,3)
return retdata(1,2,3)
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
To return multiple values in J, you return an array which contains multiple values. Since the only data type in J is array (this is an oversimplification, from some perspectives - but those issues are out of scope for this task), this is sort of like asking how to return only one value in another language.
To return multiple values in J, you return an array which contains multiple values. Since the only data type in J is array (this is an oversimplification, from some perspectives - but those issues are out of scope for this task), this is sort of like asking how to return only one value in another language.
<lang j> 1 2+3 4
<syntaxhighlight lang="j"> 1 2+3 4
4 6</lang>
4 6</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Java does not have tuples, so the most idiomatic approach would be to create a nested or inner-class specific to your values.
<syntaxhighlight lang="java">
Point getPoint() {
return new Point(1, 2);
}

static class Point {
int x, y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
</syntaxhighlight>
It is not recommended to return an ''Object'' array from a method.<br />
This will require the receiving procedure a casting operation, possibly preceded by an ''instanceof'' conditional check.<br /><br />
If you're using objects that are not known until runtime, use Java Generics.
<syntaxhighlight lang="java">
Values<String, OutputStream> getValues() {
return new Values<>("Rosetta Code", System.out);
}

static class Values<X, Y> {
X x;
Y y;

public Values(X x, Y y) {
this.x = x;
this.y = y;
}
}
</syntaxhighlight>
<br />
Or, an alternate demonstration
{{trans|NetRexx}}
{{trans|NetRexx}}
<lang Java>import java.util.List;
<syntaxhighlight lang="java">import java.util.List;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map;
Line 1,438: Line 1,839:
}
}
}
}
}</lang>
}</syntaxhighlight>
'''Otherwise'''
'''Otherwise'''
<lang Java>public class Values {
<syntaxhighlight lang="java">public class Values {
private final Object[] objects;
private final Object[] objects;
public Values(Object ... objects) {
public Values(Object ... objects) {
Line 1,470: Line 1,871:
System.out.println();
System.out.println();
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,480: Line 1,881:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
Javascript does not support multi-value bind until ECMAScript 6 is released (still a draft as of May 2015). The multi-value return is actually a destructured binding. Support may not be present yet in most implementations.
Javascript does not support multi-value bind until ECMAScript 6 is released (still a draft as of May 2015). The multi-value return is actually a destructured binding. Support may not be present yet in most implementations.
<lang JavaScript>//returns array with three values
<syntaxhighlight lang="javascript">//returns array with three values
var arrBind = function () {
var arrBind = function () {
return [1, 2, 3]; //return array of three items to assign
return [1, 2, 3]; //return array of three items to assign
Line 1,503: Line 1,904:
var {baz: foo, buz: bar} = objBind();//assigns baz => "abc", buz => "123"
var {baz: foo, buz: bar} = objBind();//assigns baz => "abc", buz => "123"
//keep rest of values together as object
//keep rest of values together as object
var {foo, ...rest} = objBind();//assigns foo => "abc, rest => {bar: "123", baz: "zzz"}</lang>
var {foo, ...rest} = objBind();//assigns foo => "abc, rest => {bar: "123", baz: "zzz"}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
jq supports streams of JSON values, so there are two main ways in which a function can return multiple values: as a stream, or as an array. Using the same example given for the Julia entry: <lang jq># To produce a stream:
jq supports streams of JSON values, so there are two main ways in which a function can return multiple values: as a stream, or as an array. Using the same example given for the Julia entry: <syntaxhighlight lang="jq"># To produce a stream:
def addsub(x; y): (x + y), (x - y);
def addsub(x; y): (x + y), (x - y);


# To produce an array:
# To produce an array:
def add_subtract(x; y): [ x+y, x-y ];
def add_subtract(x; y): [ x+y, x-y ];
</syntaxhighlight>
</lang>
The builtin filter .[] streams its input if the input is an array, e.g. the expression <code>[1,2] | .[]</code> produces the stream:<lang jq>
The builtin filter .[] streams its input if the input is an array, e.g. the expression <code>[1,2] | .[]</code> produces the stream:<syntaxhighlight lang="jq">
1
1
2</lang>
2</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>function addsub(x, y)
<syntaxhighlight lang="julia">function addsub(x, y)
return x + y, x - y
return x + y, x - y
end</lang>
end</syntaxhighlight>
<pre>julia> addsub(10,4)
<pre>julia> addsub(10,4)
(14,6)</pre>
(14,6)</pre>
Line 1,525: Line 1,926:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
Although Kotlin doesn't support tuples as such, it does have generic Pair and Triple types which can be used to return 2 or 3 values from a function. To return more values, a data class can be used. All of these types can be automatically destructured to separate named variables.
Although Kotlin doesn't support tuples as such, it does have generic Pair and Triple types which can be used to return 2 or 3 values from a function. To return more values, a data class can be used. All of these types can be automatically destructured to separate named variables.
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


/* implicitly returns a Pair<Int, Int>*/
/* implicitly returns a Pair<Int, Int>*/
Line 1,535: Line 1,936:
println("The smallest number is $min")
println("The smallest number is $min")
println("The largest number is $max")
println("The largest number is $max")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,545: Line 1,946:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Lambdatalk can retun several values glued into conses or arrays.
Lambdatalk can retun several values glued into conses or arrays.
<lang scheme>
<syntaxhighlight lang="scheme">
{def foo
{def foo
{lambda {:n}
{lambda {:n}
Line 1,561: Line 1,962:
{bar 10}
{bar 10}
-> [9,10,11]
-> [9,10,11]
</syntaxhighlight>
</lang>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define multi_value() => {
<syntaxhighlight lang="lasso">define multi_value() => {
return (:'hello word',date)
return (:'hello word',date)
}
}
Line 1,572: Line 1,973:


'x: '+#x
'x: '+#x
'\ry: '+#y</lang>
'\ry: '+#y</syntaxhighlight>
{{out}}
{{out}}
<pre>x: hello word
<pre>x: hello word
Line 1,580: Line 1,981:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Using a space-delimited string to hold the array. LB functions return only one numeric or string value, so the function returns a string from which can be separated the two desired values.
Using a space-delimited string to hold the array. LB functions return only one numeric or string value, so the function returns a string from which can be separated the two desired values.
<lang lb>data$ ="5 6 7 22 9 3 4 8 7 6 3 -5 2 1 8 9"
<syntaxhighlight lang="lb">data$ ="5 6 7 22 9 3 4 8 7 6 3 -5 2 1 8 9"


a$ =minMax$( data$)
a$ =minMax$( data$)
Line 1,600: Line 2,001:
loop until 0
loop until 0
minMax$ =str$( min) +" " +str$( max)
minMax$ =str$( min) +" " +str$( max)
end function</lang>
end function</syntaxhighlight>
<pre>
<pre>
Minimum was -5 & maximum was 22
Minimum was -5 & maximum was 22
Line 1,608: Line 2,009:
No support for returning multiple values, but (similar to Scala), a Tuple can be returned.
No support for returning multiple values, but (similar to Scala), a Tuple can be returned.


<lang Lily>define combine(a: Integer, b: String): Tuple[Integer, String]
<syntaxhighlight lang="lily">define combine(a: Integer, b: String): Tuple[Integer, String]
{
{
return <[a, b]>
return <[a, b]>
}</lang>
}</syntaxhighlight>


The current version (0.17) has no support for destructuring Tuple assigns.
The current version (0.17) has no support for destructuring Tuple assigns.


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function addsub( a, b )
<syntaxhighlight lang="lua">function addsub( a, b )
return a+b, a-b
return a+b, a-b
end
end


s, d = addsub( 7, 5 )
s, d = addsub( 7, 5 )
print( s, d )</lang>
print( s, d )</syntaxhighlight>



=={{header|M2000 Interpreter}}==
Functions can be made in 5 ways: Normal, Lambda, Simple, Group which return value, Pointer to Group which return value. For every way we can return multiple values as tuple (in a mArray type of array). The (a,b)=funcA() is a way to define/assign values from tuple. So (a,b)=(1, 2) is the simple form. A return value from a function done using = as statement. This return isn't the last statement (isn't exit from function), so may we have multiple = as statements and the last one which we execute return the value. By default if we don't use the = statement based on function's suffix at name (at call) we get 0 or "". Functions can return any type of types. So the return type based on statement = (or the interpreter return 0 or "" based on name at call, where suffix $ means we return empty string, although later versions of language can return string/ make string variables without suffix $).

<syntaxhighlight lang="m2000 interpreter">
module Return_multiple_values{
Print "Using a function"
function twovalues(x) {
="ok", x**2, x**3
}
// this is a sugar syntax to apply a tuple (mArray type) to variables
// can be new variables or pre defined
// if they are predifined then overflow may happen
byte b
// object a=(,) // if a is an object we can't assign number
(s, a,b)=twovalues(3) // twovalues(30) raise overflow
Print a=9, b=27, s="ok"
c=twovalues(3)
// need to use val$() because val() on string type is like a Val("1233")
Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
// we can pass by reference
callbyref(&twovalues())
sub callbyref(&a())
local a, b, s as string
(s, a,b)=a(3)
Print a=9, b=27, s="ok"
end sub
}
Return_multiple_values
// modules may change definitions like functions (but not subs and simple functions)
Module Return_multiple_values{
// lambdas are first citizens, can be called as functions or used as variables/values
Print "Using lambda function"
twovalues=lambda (x) ->{
="ok", x**2, x**3
}
byte b
(s, a,b)=twovalues(3) // twovalues(30) raise overflow
Print a=9, b=27, s="ok"
c=twovalues(3)
Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
callbyref(&twovalues())
callbyValue(twovalues, 3)
sub callbyref(&a())
local a, b, s as string
(s, a,b)=a(3)
Print a=9, b=27, s="ok"
end sub
sub callbyValue(g, v)
local a, b, s as string
(s, a,b)=g(v)
Print a=9, b=27, s="ok"
end sub
}
Return_multiple_values
module Return_multiple_values{
Print "Using simple function (static)"
byte b
(s, a,b)=@twovalues(3) // twovalues(30) raise overflow
Print a=9, b=27, s="ok"
c=@twovalues(3)
Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
function twovalues(x)
="ok", x**2, x**3
end function
}
Return_multiple_values
module Return_multiple_values {
// a group may used as function too
// we can use fields to alter state
// we can't pass the object as function by reference
// but we can pass an object function
// group is a static object to this module
// in every call of this module, this object initialised
// when the group statement executed
// and destroyed at the end of execution without a call to remove destructor
Print "Using a group as a function with a field"
group twovalues {
rep$="ok"
function forRef(x) {
=.rep$, x**2, x**3
}
value () { // ![] pass the stack of values to forRef function
if empty then =this: exit
=.forRef(![]) // or use =.rep$, x**2, x**3 and (x) at value
}
Set {
Error "no object change allowed"
}
}
byte b
// object a=(,) // if a is an object we can't assign number
(s, a,b)=twovalues(3)
Print a=9, b=27, s="ok"
twovalues.rep$="Yes"
c=twovalues(3)
// need to use val$() because val() on string type is like a Val("1233")
Print c#val$(0)="Yes", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
callbyref(&twovalues.forRef())
callbyValue(twovalues, 3)
sub callbyref(&a())
local a, b, s as string
(s, a,b)=a(3)
Print a=9, b=27, s="Yes"
end sub
sub callbyValue(g, v)
local a, b, s as string
(s, a,b)=g(v)
Print a=9, b=27, s="Yes"
end sub
}
Return_multiple_values

module Return_multiple_values {
Print "Using a pointer to group as a function with a field (group created by a Class)"
class iTwovalues {
string rep
function forRef(x) {
=.rep, x**2, x**3
}
value () { // ![] pass the stack of values to forRef function
=.forRef(![])
}
Set {
Error "no object change allowed"
}
// optional here, only to return the destriyed event (after the module exit from execution)
remove {
print .rep+" destroyed"
}
class:
Module iTwovalues (.rep) {
}
}
byte b
// twovalues is a pointer to an object of general type Group
twovalues->iTwovalues("ok")
Print twovalues is type iTwovalues = true
(s, a,b)=Eval(twovalues, 3)
Print a=9, b=27, s="ok"
twovalues=>rep="Yes"
c=twovalues=>forRef(3) // better to call a function instead of use Eval()
Print c#val$(0)="Yes", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
for twovalues {
// we have to use for object { } to use references to members of object
callbyref(&.forRef())
}
// if we hide the next statement we will see Yes destroyed after return from this module (before "done")
twovalues=pointer() // because twovalues is the last pointer to object, the object destroyed
// we see now: Yes destroyed
sub callbyref(&a())
local a, b, s as string
(s, a,b)=a(3)
Print a=9, b=27, s="Yes"
end sub
}
Return_multiple_values
Print "Done"
</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>> sumprod := ( a, b ) -> (a + b, a * b):
<syntaxhighlight lang="maple">> sumprod := ( a, b ) -> (a + b, a * b):
> sumprod( x, y );
> sumprod( x, y );
x + y, x y
x + y, x y


> sumprod( 2, 3 );
> sumprod( 2, 3 );
5, 6</lang>
5, 6</syntaxhighlight>
The parentheses are needed here only because of the use of arrow ("->") notation to define the procedure. One could do, instead:
The parentheses are needed here only because of the use of arrow ("->") notation to define the procedure. One could do, instead:
<lang Maple>sumprod := proc( a, b ) a + b, a * b end:</lang>
<syntaxhighlight lang="maple">sumprod := proc( a, b ) a + b, a * b end:</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>addsub [x_,y_]:= List [x+y,x-y]
<syntaxhighlight lang="mathematica">addsub [x_,y_]:= List [x+y,x-y]
addsub[4,2]</lang>
addsub[4,2]</syntaxhighlight>
{{out}}
{{out}}
<pre>{6,2}</pre>
<pre>{6,2}</pre>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang Matlab> function [a,b,c]=foo(d)
<syntaxhighlight lang="matlab"> function [a,b,c]=foo(d)
a = 1-d;
a = 1-d;
b = 2+d;
b = 2+d;
c = a+b;
c = a+b;
end;
end;
[x,y,z] = foo(5) </lang>
[x,y,z] = foo(5) </syntaxhighlight>
{{out}}
{{out}}
<lang Matlab> > [x,y,z] = foo(5)
<syntaxhighlight lang="matlab"> > [x,y,z] = foo(5)
x = -4
x = -4
y = 7
y = 7
z = 3 </lang>
z = 3 </syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>f(a, b) := [a * b, a + b]$
<syntaxhighlight lang="maxima">f(a, b) := [a * b, a + b]$


[u, v]: f(5, 6);
[u, v]: f(5, 6);
[30, 11]</lang>
[30, 11]</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
Line 1,666: Line 2,229:


===addsub.m===
===addsub.m===
<lang mercury>:- module addsub.
<syntaxhighlight lang="mercury">:- module addsub.


:- interface.
:- interface.
Line 1,693: Line 2,256:
D = X - Y.
D = X - Y.


:- end_module addsub.</lang>
:- end_module addsub.</syntaxhighlight>


===Use and output===
===Use and output===
Line 1,705: Line 2,268:
The above code can be modified so that the definition of <code>addsub/4</code> is now instead this function <code>addsub/2</code>:
The above code can be modified so that the definition of <code>addsub/4</code> is now instead this function <code>addsub/2</code>:


<lang Mercury>:- func addsub(int, int) = {int, int}.
<syntaxhighlight lang="mercury">:- func addsub(int, int) = {int, int}.
addsub(X, Y) = { X + Y, X - Y }.</lang>
addsub(X, Y) = { X + Y, X - Y }.</syntaxhighlight>


Instead, now, of a predicate with two input and two output parameters of type <code>int</code>, addsub is a function that takes two <code>int</code> parameters and returns a tuple containing two <code>int</code> values. The call to <code>addsub/4</code> in the above code is now replaced by this:
Instead, now, of a predicate with two input and two output parameters of type <code>int</code>, addsub is a function that takes two <code>int</code> parameters and returns a tuple containing two <code>int</code> values. The call to <code>addsub/4</code> in the above code is now replaced by this:


<lang Mercury> {S, D} = addsub(X, Y),</lang>
<syntaxhighlight lang="mercury"> {S, D} = addsub(X, Y),</syntaxhighlight>


All other code remains exactly the same as does the use and output of it.
All other code remains exactly the same as does the use and output of it.
Line 1,720: Line 2,283:
An example of this follows:
An example of this follows:


<lang Mercury>:- module addsub.
<syntaxhighlight lang="mercury">:- module addsub.


:- interface.
:- interface.
Line 1,747: Line 2,310:
addsub(X, Y) = twin(X + Y, X - Y).
addsub(X, Y) = twin(X + Y, X - Y).


:- end_module addsub.</lang>
:- end_module addsub.</syntaxhighlight>


Here the type <code>my_result</code> has been provided with a <code>twin/2</code> constructor that accepts two <code>int</code> values. Use and output of the code is, again, exactly the same.
Here the type <code>my_result</code> has been provided with a <code>twin/2</code> constructor that accepts two <code>int</code> values. Use and output of the code is, again, exactly the same.
Line 1,756: Line 2,319:
To return multiple values in min, simply leave them on the data stack.
To return multiple values in min, simply leave them on the data stack.
{{works with|min|0.19.6}}
{{works with|min|0.19.6}}
<lang min>(over over / '* dip) :muldiv</lang>
<syntaxhighlight lang="min">(over over / '* dip) :muldiv</syntaxhighlight>

=={{header|MIPS Assembly}}==
The registers <code>$v0</code> and <code>$v1</code> are intended for return values. Technically you can use any register you want, but the calling conventions use <code>$v0</code> and <code>$v1</code>.
<syntaxhighlight lang="mips">sum:
add $v0,$a0,$a1
jr ra
nop ;branch delay slot</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
To return multiple values in Nemerle, package them into a tuple.
To return multiple values in Nemerle, package them into a tuple.
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using Nemerle.Assertions;
using Nemerle.Assertions;
Line 1,782: Line 2,352:
WriteLine($"Min of nums = $min; max of nums = $max");
WriteLine($"Min of nums = $min; max of nums = $max");
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
Line 1,788: Line 2,358:


Another common idiom inherited from [[REXX]] is the ability to collect the return data into a simple NetRexx string. Caller can then use the <tt>PARSE</tt> instruction to deconstruct the return value and assign the parts to separate variables.
Another common idiom inherited from [[REXX]] is the ability to collect the return data into a simple NetRexx string. Caller can then use the <tt>PARSE</tt> instruction to deconstruct the return value and assign the parts to separate variables.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,890: Line 2,460:
setRightVal(sv_)
setRightVal(sv_)
return
return
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
Every function returns one value. We can return a tuple instead:
Every function returns one value. We can return a tuple instead:
<lang nim>proc addsub(x, y: int): (int, int) =
<syntaxhighlight lang="nim">proc addsub(x, y: int): (int, int) =
(x + y, x - y)
(x + y, x - y)


var (a, b) = addsub(12, 15)</lang>
var (a, b) = addsub(12, 15)</syntaxhighlight>


Or manipulate the parameters directly:
Or manipulate the parameters directly:
<lang nim>proc addsub(x, y: int; a, b: var int) =
<syntaxhighlight lang="nim">proc addsub(x, y: int; a, b: var int) =
a = x + y
a = x + y
b = x - y
b = x - y


var a, b: int
var a, b: int
addsub(12, 15, a, b)</lang>
addsub(12, 15, a, b)</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
Easiest way to return multiple values is to use in/out objects. The language also supports returning collections.
Easiest way to return multiple values is to use in/out objects. The language also supports returning collections.
<lang objeck>class Program {
<syntaxhighlight lang="objeck">class Program {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
a := IntHolder->New(3); b := IntHolder->New(7);
a := IntHolder->New(3); b := IntHolder->New(7);
Line 1,919: Line 2,489:
a->Set(a->Get() + 2); b->Set(b->Get() + 13);
a->Set(a->Get() + 2); b->Set(b->Get() + 13);
}
}
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<lang ocaml>let addsub x y =
<syntaxhighlight lang="ocaml">let addsub x y =
x + y, x - y</lang>
x + y, x - y</syntaxhighlight>
(Note that parentheses are not necessary for a tuple literal in OCaml.)
(Note that parentheses are not necessary for a tuple literal in OCaml.)


You can use pattern matching to extract the components:
You can use pattern matching to extract the components:
<lang ocaml>let sum, difference = addsub 33 12 in
<syntaxhighlight lang="ocaml">let sum, difference = addsub 33 12 in
Printf.printf "33 + 12 = %d\n" sum;
Printf.printf "33 + 12 = %d\n" sum;
Printf.printf "33 - 12 = %d\n" difference</lang>
Printf.printf "33 - 12 = %d\n" difference</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


Oforth uses a data stack. A function return is everything left on the stack when the function ends, so a function can return as many objects as needed :
Oforth uses a data stack. A function return is everything left on the stack when the function ends, so a function can return as many objects as needed :
<lang Oforth>import: date
<syntaxhighlight lang="oforth">import: date


: returnFourValues 12 13 14 15 ;
: returnFourValues 12 13 14 15 ;
Line 1,944: Line 2,514:


"\nShowing one object containing four values returned on the parameter stack:" println
"\nShowing one object containing four values returned on the parameter stack:" println
returnOneObject .s clr</lang>
returnOneObject .s clr</syntaxhighlight>


Output:
Output:
Line 1,960: Line 2,530:
=={{header|ooRexx}}==
=={{header|ooRexx}}==
Functions and methods in ooRexx can only have a single return value, but that return value can be some sort of collection or other object that contains multiple values. For example, an array:
Functions and methods in ooRexx can only have a single return value, but that return value can be some sort of collection or other object that contains multiple values. For example, an array:
<syntaxhighlight lang="oorexx">
<lang ooRexx>
r = addsub(3, 4)
r = addsub(3, 4)
say r[1] r[2]
say r[1] r[2]
Line 1,967: Line 2,537:
use arg x, y
use arg x, y
return .array~of(x + y, x - y)
return .array~of(x + y, x - y)
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,976: Line 2,546:
Demonstrated with vectors, using OOP and a pseudo-assign trick:
Demonstrated with vectors, using OOP and a pseudo-assign trick:


<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">


'============
'============
Line 2,021: Line 2,591:
print aa.ShowValues() 'result 100,200,-300,400
print aa.ShowValues() 'result 100,200,-300,400


</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
The usual way to return multiple values is to put them in a vector:
The usual way to return multiple values is to put them in a vector:
<lang parigp>foo(x)={
<syntaxhighlight lang="parigp">foo(x)={
[x^2, x^3]
[x^2, x^3]
};</lang>
};</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Functions may return lists of values:
Functions may return lists of values:
<lang perl>sub foo {
<syntaxhighlight lang="perl">sub foo {
my ($a, $b) = @_;
my ($a, $b) = @_;
return $a + $b, $a * $b;
return $a + $b, $a * $b;
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
Every function returns one value. You can return any number of items as elements of a sequence, and unpack them on receipt or not.
Every function returns one value. You can return any number of items as elements of a sequence, and unpack them on receipt or not.
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">stuff</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">stuff</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"PI"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'='</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3.1415926535</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"PI"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'='</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3.1415926535</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">{</span><span style="color: #004080;">string</span> <span style="color: #000000;">what</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">val</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stuff</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">{</span><span style="color: #004080;">string</span> <span style="color: #000000;">what</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">val</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stuff</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into an array.
Every function returns one value. The conventional way to return multiple values is to bundle them into an array.
<lang php>function addsub($x, $y) {
<syntaxhighlight lang="php">function addsub($x, $y) {
return array($x + $y, $x - $y);
return array($x + $y, $x - $y);
}</lang>
}</syntaxhighlight>
You can use the <code>list()</code> construct to assign to multiple variables:
You can use the <code>list()</code> construct to assign to multiple variables:
<lang php>list($sum, $difference) = addsub(33, 12);
<syntaxhighlight lang="php">list($sum, $difference) = addsub(33, 12);
echo "33 + 12 = $sum\n";
echo "33 + 12 = $sum\n";
echo "33 - 12 = $difference\n";</lang>
echo "33 - 12 = $difference\n";</syntaxhighlight>


Additionally, if you specify a parameter as being a pointer, you do have the capacity to change that value. A built-in PHP example of this is <code>preg_match()</code> which returns a boolean value (to determine if a match was found or not), but which modifies the <code>$matches</code> parameter supplied to hold all the capture groups.
Additionally, if you specify a parameter as being a pointer, you do have the capacity to change that value. A built-in PHP example of this is <code>preg_match()</code> which returns a boolean value (to determine if a match was found or not), but which modifies the <code>$matches</code> parameter supplied to hold all the capture groups.


You can achieve this simply by adding the <code>&</code> before the desired parameter:
You can achieve this simply by adding the <code>&</code> before the desired parameter:
<lang php>function multiples($param1, &$param2) {
<syntaxhighlight lang="php">function multiples($param1, &$param2) {
if ($param1 == 'bob') {
if ($param1 == 'bob') {
$param2 = 'is your grandmother';
$param2 = 'is your grandmother';
Line 2,072: Line 2,642:


echo 'Second run: ' . multiples('bob', $y) . "\r\n";
echo 'Second run: ' . multiples('bob', $y) . "\r\n";
echo "Param 2 from second run: '${y}'\r\n";</lang>
echo "Param 2 from second run: '${y}'\r\n";</syntaxhighlight>


The above will yield the following output:
The above will yield the following output:
Line 2,079: Line 2,649:
Second run: 1
Second run: 1
Param 2 from second run: 'is your grandmother'</pre>
Param 2 from second run: 'is your grandmother'</pre>

=={{header|Picat}}==
===Functions===
Functions returns a single value. Multiple values must be collected in a list (or an array, map, set, structure).
<syntaxhighlight lang="picat">main =>
[A,B,C] = fun(10),
println([A,B,C]).

fun(N) = [2*N-1,2*N,2*N+1].</syntaxhighlight>

===Predicates===
Sometimes it is not possible - or not convenient - to create a function that return values. In those cases a predicate is used and then some of the variables are considered output variables (and are usually placed last).
<syntaxhighlight lang="picat">main =>
pred(10, E,F,G),
% ...

% A, B, and C are output variables
pred(N, A,B,C) =>
A=2*N-1,
B=2*N,
C=2*N+1.</syntaxhighlight>

A variant of this is to use a structure (here <code>$ret(A,B,C)</code>) that collects the output values.
<syntaxhighlight lang="picat">main =>
pred2(10, Ret),
println(Ret),
% or
pred2(10,$ret(H,I,J)),
println([H,I,J]).

% The structure $ret(A,B,C) contains the output values.
pred2(N, ret(A,B,C)) :-
A=2*N-1,
B=2*N,
C=2*N+1.</syntaxhighlight>

Note: Sometimes the meaning of input/output variables are confusing, for example when a predicate can be used with multiple input/output modes, e.g. reversible predicates such as <code>append/3</code> or <code>member/2</code>.




=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
A PicoLisp function returns a single value. For multiple return values, a cons pair or a list may be used.
A PicoLisp function returns a single value. For multiple return values, a cons pair or a list may be used.
<lang PicoLisp>(de addsub (X Y)
<syntaxhighlight lang="picolisp">(de addsub (X Y)
(list (+ X Y) (- X Y)) )</lang>
(list (+ X Y) (- X Y)) )</syntaxhighlight>
Test:
Test:
<lang PicoLisp>: (addsub 4 2)
<syntaxhighlight lang="picolisp">: (addsub 4 2)
-> (6 2)
-> (6 2)
: (addsub 3 1)
: (addsub 3 1)
Line 2,092: Line 2,701:
-> 10
-> 10
: (sum + (addsub 4 2) (addsub 3 1))
: (sum + (addsub 4 2) (addsub 3 1))
-> 14</lang>
-> 14</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
Multiple values are returned through an array.
Multiple values are returned through an array.
An array can be assigned to separate variables.
An array can be assigned to separate variables.
<lang Pike>array(int) addsub(int x, int y)
<syntaxhighlight lang="pike">array(int) addsub(int x, int y)
{
{
return ({ x+y, x-y });
return ({ x+y, x-y });
}
}


[int z, int w] = addsub(5,4);</lang>
[int z, int w] = addsub(5,4);</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
Example 1 illustrates a function that returns an array:
Example 1 illustrates a function that returns an array:
<lang PL/I> define structure 1 h,
<syntaxhighlight lang="pl/i"> define structure 1 h,
2 a (10) float;
2 a (10) float;
declare i fixed binary;
declare i fixed binary;
Line 2,117: Line 2,726:
end;
end;
return (p);
return (p);
end sub;</lang>
end sub;</syntaxhighlight>
Example 2 illustrates a function that returns a general data structure:
Example 2 illustrates a function that returns a general data structure:
<lang PL/I> define structure 1 customer,
<syntaxhighlight lang="pl/i"> define structure 1 customer,
2 name,
2 name,
3 surname character (20),
3 surname character (20),
Line 2,133: Line 2,742:
get edit (c.street, c.suburb, c.zip) (L);
get edit (c.street, c.suburb, c.zip) (L);
return (c);
return (c);
end sub2;</lang>
end sub2;</syntaxhighlight>
Example 3 illustrates the return of two values as a complex value:
Example 3 illustrates the return of two values as a complex value:
<lang PL/I>comp: procedure(a, b) returns (complex);
<syntaxhighlight lang="pl/i">comp: procedure(a, b) returns (complex);
declare (a, b) float;
declare (a, b) float;


return (complex(a, b) );
return (complex(a, b) );
end comp;</lang>
end comp;</syntaxhighlight>


=={{header|Plain English}}==
=={{header|Plain English}}==
Since parameters are passed by reference by default in Plain English, returning values ends up being unnecessary in most cases. The only functions that actually return a value are Boolean functions, called deciders.
Returning multiple values is natural. There are no limits to which parameters may be used for inputs and which parameters may be used for outputs. It's all the same to Plain English. You choose which slot(s) to put your return value(s) into.


It is possible, however, to call an auxiliary routine to change fields in a record and:
Notice that the outputs actually come before the inputs in this case. (You could even have the outputs overwrite the inputs if you want.) In the calling scope, <code>a product</code> and <code>a quotient</code> introduce new local variables containing the values placed into them by the routine.
<lang plainenglish>To run:
Start up.
Compute a product and a quotient given 15 and 3.
Write "The product is " then the product on the console.
Write "The quotient is " then the quotient on the console.
Wait for the escape key.
Shut down.


# Concatenate these values, assigning the concatenated string to a new string (see code below);
A product is a number.
# Write the concatenated string on the console; or
# As is done in C style, obtain the address of the record (a pointer) and save the pointer's value in a number for later manipulation.


<syntaxhighlight line="1" start="1">The example record is a record with
To compute a product and a quotient given a number and another number:
Put the number times the other number into the product.
A number called first field,
A string called second field,
Put the number divided by the other number into the quotient.</lang>
A flag called third field.
{{out}}
To run:
Start up.
Fill the example record.
Write the example record on the console.
Shut down.

To fill the example record:
Put 123 into the example's record's first field.
Put "Hello World!" into the example's record's second field.
Set the example's record's third field.

To Write the example record on the console:
Convert the example's example's record's first field to a string.
Convert the example's example's record's third field to another string.
Put the string then " "
then the example's record's second field
then " " then other string into a return string.
Write the return string on the console.
</syntaxhighlight>When it is necessary to get the return value from a Win 32 API function, the syntax is as follows:

''Call "dllname.dll" "FunctionNameHereIsCaseSensitive" returning a <type>.''

Example:s

''Call "gdi32.dll" "GetCurrentObject" with the printer canvas and 6 [obj_font] returning a handle.''

''Call "kernel32.dll" "SetFilePointer" with the file and 0 and 0 and 2 [file_end] returning a result number.''

''Call "kernel32.dll" "WriteFile" with the file and the buffer's first and the buffer's length and a number's whereabouts and 0 returning the result number.''

''Call "kernel32.dll" "HeapAlloc" with the heap pointer and 8 [heap_zero_memory] and the byte count returning the pointer.''{{out}}
<pre>
<pre>
123 Hello World! yes
The product is 45
The quotient is 5
</pre>
</pre>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function multiple-value ($a, $b) {
function multiple-value ($a, $b) {
[pscustomobject]@{
[pscustomobject]@{
Line 2,175: Line 2,810:
$m.a
$m.a
$m.b
$m.b
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,186: Line 2,821:


An array, map, or list can be used as a parameter to a procedure and in the process contain values to be returned as well. A pointer to memory or a structured variable may also be returned to reference multiple return values (requiring the memory to be manually freed afterwards).
An array, map, or list can be used as a parameter to a procedure and in the process contain values to be returned as well. A pointer to memory or a structured variable may also be returned to reference multiple return values (requiring the memory to be manually freed afterwards).
<lang purebasic>;An array, map, or list can be used as a parameter to a procedure and in the
<syntaxhighlight lang="purebasic">;An array, map, or list can be used as a parameter to a procedure and in the
;process contain values to be returned as well.
;process contain values to be returned as well.
Procedure example_1(x, y, Array r(1)) ;array r() will contain the return values
Procedure example_1(x, y, Array r(1)) ;array r() will contain the return values
Line 2,218: Line 2,853:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.
Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.
<lang python>def addsub(x, y):
<syntaxhighlight lang="python">def addsub(x, y):
return x + y, x - y</lang>
return x + y, x - y</syntaxhighlight>
(Note that parentheses are not necessary for a tuple literal in Python.)
(Note that parentheses are not necessary for a tuple literal in Python.)


You can assign to a comma-separated list of targets:
You can assign to a comma-separated list of targets:
<lang python>sum, difference = addsub(33, 12)
<syntaxhighlight lang="python">sum, difference = addsub(33, 12)
print "33 + 12 = %s" % sum
print "33 + 12 = %s" % sum
print "33 - 12 = %s" % difference</lang>
print "33 - 12 = %s" % difference</syntaxhighlight>
There is no discernible difference between "returning multiple values" and returning a single tuple of multiple values. It is just a more pedantic/accurate statement of the mechanism employed.
There is no discernible difference between "returning multiple values" and returning a single tuple of multiple values. It is just a more pedantic/accurate statement of the mechanism employed.


Line 2,253: Line 2,888:
=={{header|R}}==
=={{header|R}}==
The conventional way to return multiple values is to bundle them into a list.
The conventional way to return multiple values is to bundle them into a list.
<lang R>addsub <- function(x, y) list(add=(x + y), sub=(x - y))</lang>
<syntaxhighlight lang="r">addsub <- function(x, y) list(add=(x + y), sub=(x - y))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Racket has a defined function "values" that returns multiple values using continuations, a way it can be implemented is shown in "my-values"
Racket has a defined function "values" that returns multiple values using continuations, a way it can be implemented is shown in "my-values"
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(values 4 5)
(values 4 5)


Line 2,263: Line 2,898:
(call/cc
(call/cc
(lambda (return)
(lambda (return)
(apply return return-list))))</lang>
(apply return return-list))))</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,270: Line 2,905:
Each function officially returns one value, but by returning a List or Seq you can transparently return a list of arbitrary (even infinite) size. The calling scope can destructure the list using assignment, if it so chooses:
Each function officially returns one value, but by returning a List or Seq you can transparently return a list of arbitrary (even infinite) size. The calling scope can destructure the list using assignment, if it so chooses:


<lang perl6>sub addmul($a, $b) {
<syntaxhighlight lang="raku" line>sub addmul($a, $b) {
$a + $b, $a * $b
$a + $b, $a * $b
}
}


my ($add, $mul) = addmul 3, 7;</lang>
my ($add, $mul) = addmul 3, 7;</syntaxhighlight>


In this example, the variable <tt>$add</tt> now holds the number 10, and <tt>$mul</tt> the number 21.
In this example, the variable <tt>$add</tt> now holds the number 10, and <tt>$mul</tt> the number 21.


=={{header|Raven}}==
=={{header|Raven}}==
<lang Raven>define multiReturn use $v
<syntaxhighlight lang="raven">define multiReturn use $v
$v each
$v each


3 multiReturn</lang>
3 multiReturn</syntaxhighlight>
{{out}}
{{out}}
<pre>2
<pre>2
1
1
0</pre>
0</pre>

=={{header|ReScript}}==
<syntaxhighlight lang="rescript">let addsub = (x, y) => {
(x + y, x - y)
}

let (sum, difference) = addsub(33, 12)

Js.log2("33 + 12 = ", sum)
Js.log2("33 - 12 = ", difference)</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
Functions take and return values via a stack. This makes returning multiple values easy.
Functions take and return values via a stack. This makes returning multiple values easy.
<lang Retro>: addSubtract ( xy-nm )
<syntaxhighlight lang="retro">: addSubtract ( xy-nm )
2over - [ + ] dip ;</lang>
2over - [ + ] dip ;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 2,300: Line 2,945:
<br>semicolon, backslash, ···], &nbsp; it's a very simple matter to parse the multiple-value string into the desired
<br>semicolon, backslash, ···], &nbsp; it's a very simple matter to parse the multiple-value string into the desired
<br>substrings &nbsp; (or values, if you will) &nbsp; with REXX's handy-dandy &nbsp; '''parse''' &nbsp; statement.
<br>substrings &nbsp; (or values, if you will) &nbsp; with REXX's handy-dandy &nbsp; '''parse''' &nbsp; statement.
<lang REXX>/*REXX program shows and displays examples of multiple RETURN values from a function.*/
<syntaxhighlight lang="rexx">/*REXX program shows and displays examples of multiple RETURN values from a function.*/
numeric digits 70 /*the default is: NUMERIC DIGITS 9 */
numeric digits 70 /*the default is: NUMERIC DIGITS 9 */
parse arg a b . /*obtain two numbers from command line.*/
parse arg a b . /*obtain two numbers from command line.*/
Line 2,320: Line 2,965:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
arithmetics: procedure; parse arg x,y; return x||y x+y x-y x//y x/y x%y x*y x**y</lang>
arithmetics: procedure; parse arg x,y; return x||y x+y x-y x//y x/y x%y x*y x**y</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 2,337: Line 2,982:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
Func AddSub x,y
Func AddSub x,y
Return [ x+y, x-y ]
Return [ x+y, x-y ]
</syntaxhighlight>
</lang>

=={{header|RPL}}==
The stack is where data are taken and then returned: stack size's the limit!
≪ + LAST - ≫ ‘ADDSUB’ STO
{{in}}
<pre>
33 12 ADDSUB
</pre>
{{out}}
<pre>
2: 44
1: 20
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 2,346: Line 3,004:


Use an array literal:
Use an array literal:
<lang ruby>def addsub(x, y)
<syntaxhighlight lang="ruby">def addsub(x, y)
[x + y, x - y]
[x + y, x - y]
end</lang>
end</syntaxhighlight>
Or use <code>return</code> with 2 or more values:
Or use <code>return</code> with 2 or more values:
<lang ruby>def addsub(x, y)
<syntaxhighlight lang="ruby">def addsub(x, y)
return x + y, x - y
return x + y, x - y
end</lang>
end</syntaxhighlight>


(With at least 2 values, <code>return</code> makes a new Array. With 1 value, <code>return</code> passes the value, without making any Array. With 0 values, <code>return</code> passes <code>nil</code>.)
(With at least 2 values, <code>return</code> makes a new Array. With 1 value, <code>return</code> passes the value, without making any Array. With 0 values, <code>return</code> passes <code>nil</code>.)


Assignment can split the Array into separate variables.
Assignment can split the Array into separate variables.
<lang ruby>sum, difference = addsub(33, 12)
<syntaxhighlight lang="ruby">sum, difference = addsub(33, 12)
puts "33 + 12 = #{sum}"
puts "33 + 12 = #{sum}"
puts "33 - 12 = #{difference}"</lang>
puts "33 - 12 = #{difference}"</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
Courtesy http://dkokenge.com/rbp
Courtesy http://dkokenge.com/rbp
<br>Gets the UTC time from the web
<br>Gets the UTC time from the web
<lang runbasic>a$ = timeInfo$()
<syntaxhighlight lang="runbasic">a$ = timeInfo$()
print " UTC:";word$(a$,1,"|")
print " UTC:";word$(a$,1,"|")
print "Date:";word$(a$,2,"|")
print "Date:";word$(a$,2,"|")
Line 2,374: Line 3,032:
t$ = time$()
t$ = time$()
timeInfo$ = utc$;"|";d$;"|";t$
timeInfo$ = utc$;"|";d$;"|";t$
end function</lang>
end function</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Line 2,380: Line 3,038:
Rust supports ADT, thus function can return tuple.
Rust supports ADT, thus function can return tuple.


<lang rust>fn multi_hello() -> (&'static str, i32) {
<syntaxhighlight lang="rust">fn multi_hello() -> (&'static str, i32) {
("Hello",42)
("Hello",42)
}
}
Line 2,388: Line 3,046:
println!("{},{}",str,num);
println!("{},{}",str,num);
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,397: Line 3,055:
=={{header|Scala}}==
=={{header|Scala}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<lang scala>def addSubMult(x: Int, y: Int) = (x + y, x - y, x * y)</lang>
<syntaxhighlight lang="scala">def addSubMult(x: Int, y: Int) = (x + y, x - y, x * y)</syntaxhighlight>
A more detailed declaration would be:
A more detailed declaration would be:
<lang scala>
<syntaxhighlight lang="scala">
def addSubMult(x: Int, y:Int) : (Int, Int, Int) = {
def addSubMult(x: Int, y:Int) : (Int, Int, Int) = {
...
...
(x + y, x - y, x * y)
(x + y, x - y, x * y)
}
}
</syntaxhighlight>
</lang>
You can use pattern matching to extract the components:
You can use pattern matching to extract the components:
<lang scala>val (sum, difference) = addsub(33, 12)</lang>
<syntaxhighlight lang="scala">val (sum, difference) = addsub(33, 12)</syntaxhighlight>
Scala borrows this idea from ML, and generalizes it into [http://www.scala-lang.org/node/112 extractors].
Scala borrows this idea from ML, and generalizes it into [http://www.scala-lang.org/node/112 extractors].


=={{header|Scheme}}==
=={{header|Scheme}}==
Scheme can return multiple values using the <code>values</code> function, which uses continuations:
Scheme can return multiple values using the <code>values</code> function, which uses continuations:
<lang scheme>(define (addsub x y)
<syntaxhighlight lang="scheme">(define (addsub x y)
(values (+ x y) (- x y)))</lang>
(values (+ x y) (- x y)))</syntaxhighlight>
You can use the multiple values using the <code>call-with-values</code> function:
You can use the multiple values using the <code>call-with-values</code> function:
<lang scheme>(call-with-values
<syntaxhighlight lang="scheme">(call-with-values
(lambda () (addsub 33 12))
(lambda () (addsub 33 12))
(lambda (sum difference)
(lambda (sum difference)
(display "33 + 12 = ") (display sum) (newline)
(display "33 + 12 = ") (display sum) (newline)
(display "33 - 12 = ") (display difference) (newline)))</lang>
(display "33 - 12 = ") (display difference) (newline)))</syntaxhighlight>
The syntax is kinda awkward. SRFI 8 introduces a <code>receive</code> construct to make this simpler:
The syntax is kinda awkward. SRFI 8 introduces a <code>receive</code> construct to make this simpler:
<lang scheme>(receive (sum difference) (addsub 33 12)
<syntaxhighlight lang="scheme">(receive (sum difference) (addsub 33 12)
; in this scope you can use sum and difference
; in this scope you can use sum and difference
(display "33 + 12 = ") (display sum) (newline)
(display "33 + 12 = ") (display sum) (newline)
(display "33 - 12 = ") (display difference) (newline))</lang>
(display "33 - 12 = ") (display difference) (newline))</syntaxhighlight>
SRFI 11 introduces a <code>let-values</code> construct to make this simpler:
SRFI 11 introduces a <code>let-values</code> construct to make this simpler:
<lang scheme>(let-values (((sum difference) (addsub 33 12)))
<syntaxhighlight lang="scheme">(let-values (((sum difference) (addsub 33 12)))
; in this scope you can use sum and difference
; in this scope you can use sum and difference
(display "33 + 12 = ") (display sum) (newline)
(display "33 + 12 = ") (display sum) (newline)
(display "33 - 12 = ") (display difference) (newline))</lang>
(display "33 - 12 = ") (display difference) (newline))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Seed7 functions can only return one value. That value could be an array or record holding multiple values, but the usual method for returning several values is using a procedure with [http://seed7.sourceforge.net/manual/params.htm#inout_parameter inout] parameters:
Seed7 functions can only return one value. That value could be an array or record holding multiple values, but the usual method for returning several values is using a procedure with [http://seed7.sourceforge.net/manual/params.htm#inout_parameter inout] parameters:
<lang Seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: sumAndDiff (in integer: x, in integer: y, inout integer: sum, inout integer: diff) is func
const proc: sumAndDiff (in integer: x, in integer: y, inout integer: sum, inout integer: diff) is func
Line 2,448: Line 3,106:
writeln("Sum: " <& sum);
writeln("Sum: " <& sum);
writeln("Diff: " <& diff);
writeln("Diff: " <& diff);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 2,458: Line 3,116:
=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
You can return multiple values in SenseTalk by returning a list, which can be assigned to multiple variables.
You can return multiple values in SenseTalk by returning a list, which can be assigned to multiple variables.
<lang sensetalk>set [quotient,remainder] to quotientAndRemainder(13,4)
<syntaxhighlight lang="sensetalk">set [quotient,remainder] to quotientAndRemainder(13,4)


put !"The quotient of 13 ÷ 4 is: [[quotient]] with remainder: [[remainder]]"
put !"The quotient of 13 ÷ 4 is: [[quotient]] with remainder: [[remainder]]"
Line 2,464: Line 3,122:
to handle quotientAndRemainder of num, divisor
to handle quotientAndRemainder of num, divisor
return [num div divisor, num rem divisor]
return [num div divisor, num rem divisor]
end quotientAndRemainder</lang>
end quotientAndRemainder</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,471: Line 3,129:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func foo(a,b) {
<syntaxhighlight lang="ruby">func foo(a,b) {
return (a+b, a*b);
return (a+b, a*b);
}</lang>
}</syntaxhighlight>


Catching the returned arguments:
Catching the returned arguments:
<lang ruby>var (x, y) = foo(4, 5);
<syntaxhighlight lang="ruby">var (x, y) = foo(4, 5);
say x; #=> 9
say x; #=> 9
say y; #=> 20</lang>
say y; #=> 20</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 2,484: Line 3,142:
Smalltalk returns a single value from methods, so this task is usually implemented the scheme-way, by passing a lambda-closure which is invoked with the values to return and either operates on the values itself or sets them as the caller's locals (i.e. simular to call-with-values ... values):
Smalltalk returns a single value from methods, so this task is usually implemented the scheme-way, by passing a lambda-closure which is invoked with the values to return and either operates on the values itself or sets them as the caller's locals (i.e. simular to call-with-values ... values):


<lang smalltalk>foo multipleValuesInto:[:a :b |
<syntaxhighlight lang="smalltalk">foo multipleValuesInto:[:a :b |
Transcript show:a; cr.
Transcript show:a; cr.
Transcript show:b; cr.
Transcript show:b; cr.
]</lang>
]</syntaxhighlight>


or:
or:
<lang smalltalk>|val1 val2|
<syntaxhighlight lang="smalltalk">|val1 val2|
foo multipleValuesInto:[:a :b |
foo multipleValuesInto:[:a :b |
val1 := a.
val1 := a.
Line 2,496: Line 3,154:
].
].
... do something with val1 and val2...
... do something with val1 and val2...
</syntaxhighlight>
</lang>


The called method in foo looks like:
The called method in foo looks like:
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
multipleValuesInto: aTwoArgBlock
multipleValuesInto: aTwoArgBlock
...
...
aTwoArgBlock value:<value1> value:<value2>
aTwoArgBlock value:<value1> value:<value2>
</syntaxhighlight>
</lang>
i.e. it invokes the passed-in lambda closure with the two (return-)values.
i.e. it invokes the passed-in lambda closure with the two (return-)values.


=={{header|Standard ML}}==
=={{header|Standard ML}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<lang sml>fun addsub (x, y) =
<syntaxhighlight lang="sml">fun addsub (x, y) =
(x + y, x - y)</lang>
(x + y, x - y)</syntaxhighlight>
You can use pattern matching to extract the components:
You can use pattern matching to extract the components:
<lang sml>let
<syntaxhighlight lang="sml">let
val (sum, difference) = addsub (33, 12)
val (sum, difference) = addsub (33, 12)
in
in
print ("33 + 12 = " ^ Int.toString sum ^ "\n");
print ("33 + 12 = " ^ Int.toString sum ^ "\n");
print ("33 - 12 = " ^ Int.toString difference ^ "\n")
print ("33 - 12 = " ^ Int.toString difference ^ "\n")
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.
Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.
<lang swift>func addsub(x: Int, y: Int) -> (Int, Int) {
<syntaxhighlight lang="swift">func addsub(x: Int, y: Int) -> (Int, Int) {
return (x + y, x - y)
return (x + y, x - y)
}</lang>
}</syntaxhighlight>
You can use pattern matching to extract the components:
You can use pattern matching to extract the components:
<lang swift>let (sum, difference) = addsub(33, 12)
<syntaxhighlight lang="swift">let (sum, difference) = addsub(33, 12)
println("33 + 12 = \(sum)")
println("33 + 12 = \(sum)")
println("33 - 12 = \(difference)")</lang>
println("33 - 12 = \(difference)")</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Tcl commands all return a single value, but this value can be a compound value such as a list or dictionary. The result value of a procedure is either the value given to the <code>return</code> command or the result of the final command in the body in the procedure. (Commands that return “no” value actually return the empty string.)
Tcl commands all return a single value, but this value can be a compound value such as a list or dictionary. The result value of a procedure is either the value given to the <code>return</code> command or the result of the final command in the body in the procedure. (Commands that return “no” value actually return the empty string.)
<lang tcl>proc addsub {x y} {
<syntaxhighlight lang="tcl">proc addsub {x y} {
list [expr {$x+$y}] [expr {$x-$y}]
list [expr {$x+$y}] [expr {$x-$y}]
}</lang>
}</syntaxhighlight>
This can be then assigned to a single variable with <code>set</code> or to multiple variables with <code>lassign</code>.
This can be then assigned to a single variable with <code>set</code> or to multiple variables with <code>lassign</code>.
<lang tcl>lassign [addsub 33 12] sum difference
<syntaxhighlight lang="tcl">lassign [addsub 33 12] sum difference
puts "33 + 12 = $sum, 33 - 12 = $difference"</lang>
puts "33 + 12 = $sum, 33 - 12 = $difference"</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Line 2,541: Line 3,199:


The following function potentially returns three values, which will happen if called with three arguments, each of which is an unbound variable:
The following function potentially returns three values, which will happen if called with three arguments, each of which is an unbound variable:
<lang txr>@(define func (x y z))
<syntaxhighlight lang="txr">@(define func (x y z))
@ (bind w "discarded")
@ (bind w "discarded")
@ (bind (x y z) ("a" "b" "c"))
@ (bind (x y z) ("a" "b" "c"))
@(end)</lang>
@(end)</syntaxhighlight>
The binding <code>w</code>, if created, is discarded because <code>w</code> is not in the list of formal parameters. However, <code>w</code> can cause the function to fail because there can already exist a variable <code>w</code> with a value which doesn't match <code>"discarded"</code>.
The binding <code>w</code>, if created, is discarded because <code>w</code> is not in the list of formal parameters. However, <code>w</code> can cause the function to fail because there can already exist a variable <code>w</code> with a value which doesn't match <code>"discarded"</code>.


Call:
Call:
<lang txr>@(func t r s)</lang>
<syntaxhighlight lang="txr">@(func t r s)</syntaxhighlight>
If <code>t</code>, <code>r</code> and <code>s</code> are unbound variables, they get bound to <code>"a"</code>, <code>"b"</code> and <code>"c"</code>, respectively via a renaming mechanism. This may look like C++ reference parameters or Pascal "var" parameters, and can be used that way, but isn't really the same at all.
If <code>t</code>, <code>r</code> and <code>s</code> are unbound variables, they get bound to <code>"a"</code>, <code>"b"</code> and <code>"c"</code>, respectively via a renaming mechanism. This may look like C++ reference parameters or Pascal "var" parameters, and can be used that way, but isn't really the same at all.


Failed call ("1" doesn't match "a"):
Failed call ("1" doesn't match "a"):
<lang txr>@(func "1" r s)</lang>
<syntaxhighlight lang="txr">@(func "1" r s)</syntaxhighlight>
Successful call binding only one new variable:
Successful call binding only one new variable:
<lang txr>@(func "a" "b" s)</lang>
<syntaxhighlight lang="txr">@(func "a" "b" s)</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 2,560: Line 3,218:
it can be simulated through some clunky code.
it can be simulated through some clunky code.


<lang bash>
<syntaxhighlight lang="bash">
#!/bin/sh
#!/bin/sh
funct1() {
funct1() {
Line 2,575: Line 3,233:
echo "x=$x"
echo "x=$x"
echo "y=$y"
echo "y=$y"
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,587: Line 3,245:


This example gets a specified amount of strings from the user, then returns a stream containing them.
This example gets a specified amount of strings from the user, then returns a stream containing them.
<lang ursa>def getstrs (int n)
<syntaxhighlight lang="ursa">def getstrs (int n)
decl string<> input
decl string<> input


Line 2,606: Line 3,264:
set ret (getstrs amount)
set ret (getstrs amount)


out endl ret endl console</lang>
out endl ret endl console</syntaxhighlight>
{{out}}
{{out}}
<pre>how many strings do you want to enter? 5
<pre>how many strings do you want to enter? 5
Line 2,619: Line 3,277:
=={{header|VBA}}==
=={{header|VBA}}==
Firt way : User Defined Type
Firt way : User Defined Type
<syntaxhighlight lang="vb">
<lang vb>
Type Contact
Type Contact
Name As String
Name As String
Line 2,639: Line 3,297:
Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old."
Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old."
End Sub
End Sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>SMITH John, 23 years old.</pre>
<pre>SMITH John, 23 years old.</pre>
Second way : ByRef argument : (Note : the ByRef Arg could be an array)
Second way : ByRef argument : (Note : the ByRef Arg could be an array)
<syntaxhighlight lang="vb">
<lang vb>
Function Divide(Dividend As Integer, Divisor As Integer, ByRef Result As Double) As Boolean
Function Divide(Dividend As Integer, Divisor As Integer, ByRef Result As Double) As Boolean
Divide = True
Divide = True
Line 2,665: Line 3,323:
Debug.Print "Divide return : " & B & " Result = " & R
Debug.Print "Divide return : " & B & " Result = " & R
End Sub
End Sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Divide return : True Result = 3,33333333333333
<pre>Divide return : True Result = 3,33333333333333
Divide return : False Result = 1,#INF</pre>
Divide return : False Result = 1,#INF</pre>
Third way : ParramArray
Third way : ParramArray
<syntaxhighlight lang="vb">
<lang vb>
Function Multiple_Divide(Dividend As Integer, Divisor As Integer, ParamArray numbers() As Variant) As Long
Function Multiple_Divide(Dividend As Integer, Divisor As Integer, ParamArray numbers() As Variant) As Long
Dim i As Integer
Dim i As Integer
Line 2,705: Line 3,363:
Next i
Next i
End Sub
End Sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>The function return : 1
<pre>The function return : 1
Line 2,721: Line 3,379:
vbNullString</pre>
vbNullString</pre>
Fourth way : the variant() function
Fourth way : the variant() function
<syntaxhighlight lang="vb">
<lang vb>
Function List() As String()
Function List() As String()
Dim i&, Temp(9) As String
Dim i&, Temp(9) As String
Line 2,740: Line 3,398:
Next
Next
End Sub
End Sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Liste 1
<pre>Liste 1
Line 2,754: Line 3,412:


=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
<lang vfp>
<syntaxhighlight lang="vfp">
*!* Return multiple values from a function
*!* Return multiple values from a function
*!* The simplest way is to pass the parameters by reference
*!* The simplest way is to pass the parameters by reference
Line 2,772: Line 3,430:
RETURN n
RETURN n
ENDFUNC
ENDFUNC
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
In Wren, one would return multiple values from a function or method by using some sort of Sequence object, usually a List though a Map could be used if you needed ''named'' returns.
In Wren, one would return multiple values from a function or method by using some sort of Sequence object, usually a List though a Map could be used if you needed ''named'' returns.
<lang ecmascript>var splitName = Fn.new { |fullName| fullName.split(" ") }
<syntaxhighlight lang="wren">var splitName = Fn.new { |fullName| fullName.split(" ") }


var names = splitName.call("George Bernard Shaw")
var names = splitName.call("George Bernard Shaw")
System.print("First name: %(names[0]), middle name: %(names[1]) and surname: %(names[2]).")</lang>
System.print("First name: %(names[0]), middle name: %(names[1]) and surname: %(names[2]).")</syntaxhighlight>


{{out}}
{{out}}
Line 2,787: Line 3,445:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations


proc Rect2Polar(X,Y,A,D); \Return two polar coordinate values
proc Rect2Polar(X,Y,A,D); \Return two polar coordinate values
Line 2,800: Line 3,458:
RlOut(0, Dist);
RlOut(0, Dist);
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}} (angle is in radians):
{{out}} (angle is in radians):
Line 2,806: Line 3,464:
0.64350 5.00000
0.64350 5.00000
</pre>
</pre>

=={{header|Z80 Assembly}}==
A function can return multiple values by altering the contents of multiple registers. Code is <code>CALL</code>ed as a subroutine.

In this trivial example, the function returns 0xABCD and 0xFFFF.
<syntaxhighlight lang="z80">foo:
ld hl,&ABCD
ld bc,&FFFF
ret</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn f{return(1,2,"three")}
<syntaxhighlight lang="zkl">fcn f{return(1,2,"three")}
a,b,c:=f() // a==1, b==2, c=="three"</lang>
a,b,c:=f() // a==1, b==2, c=="three"</syntaxhighlight>

Latest revision as of 16:44, 22 February 2024

Task
Return multiple values
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Show how to return more than one value from a function.

11l

Translation of: Python
F addsub(x, y)
   R (x + y, x - y)

V (summ, difference) = addsub(33, 12)
print(‘33 + 12 = ’summ)
print(‘33 - 12 = ’difference)
Output:
33 + 12 = 45
33 - 12 = 21

6502 Assembly

A function can return multiple values by storing them in two or more registers, or in user RAM. Functions are typically called as a subroutine, e.g. JSR UnpackNibbles.

UnpackNibbles:
; Takes accumulator as input. 
; Separates a two-digit hex number into its component "nibbles." Left nibble in X, right nibble in Y.

pha          ;backup the input.
and #$0F     ;chop off the left nibble. What remains is our Y.
tay
pla          ;restore input
and #$F0     ;chop off the right nibble. What remains is our X, but it needs to be bit shifted into the right nibble.
lsr
lsr
lsr
lsr
tax          ;store in X
rts

68000 Assembly

Translation of: ARM Assembly

A function's "return value" is nothing more than the register state upon exit. However, to ensure compatibility between software, there are general calling conventions that compiler-written code will follow that standardizes which registers are used to return values from a function.

This code returns the sum and difference of two integers, which will be passed in via registers D2 and D3. D2+D3 is returned in D0, D2-D3 is returned in D1.

foo:
MOVE.L D2,D0
MOVE.L D3,D1
ADD.L D1,D0
SUB.L D2,D3
MOVE.L D3,D1
RTS

8086 Assembly

Translation of: ARM Assembly

A function's "return value" is nothing more than the register state upon exit. However, to ensure compatibility between software, there are general calling conventions that compiler-written code will follow that standardizes which registers are used to return values from a function.

This function takes two 16-bit numbers in CX and DX, and outputs their sum to AX and their difference to BX.

mov ax,cx
mov bx,dx
add ax,bx
sub cx,dx
mov bx,cx
ret

ACL2

;; To return multiple values:
(defun multiple-values (a b)
   (mv a b))

;; To extract the values:
(mv-let (x y)
        (multiple-values 1 2)
   (+ x y))



Action!

The user must type in the monitor the following command after compilation and before running the program!

SET EndProg=*
CARD EndProg ;required for ALLOCATE.ACT

INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!

DEFINE PTR="CARD"
DEFINE RECORD_SIZE="6"
TYPE Record=[CARD min,max,sum]

PROC ArgumentsAsPointers(CARD ARRAY a BYTE n CARD POINTER min,max,sum)
  BYTE i

  min^=65535 max^=0 sum^=0
  FOR i=0 TO n-1
  DO
    IF a(i)>max^ THEN
      max^=a(i)
    FI
    IF a(i)<min^ THEN
      min^=a(i)
    FI
    sum^==+a(i)
  OD
RETURN

PROC ArgumentAsRecord(CARD ARRAY a BYTE n Record POINTER res)
  BYTE i

  res.min=65535 res.max=0 res.sum=0
  FOR i=0 TO n-1
  DO
    IF a(i)>res.max THEN
      res.max=a(i)
    FI
    IF a(i)<res.min THEN
      res.min=a(i)
    FI
    res.sum==+a(i)
  OD
RETURN

PTR FUNC ResultAsRecord(CARD ARRAY a BYTE n)
  Record POINTER res
  BYTE i

  res=Alloc(RECORD_SIZE)
  res.min=65535 res.max=0 res.sum=0
  FOR i=0 TO n-1
  DO
    IF a(i)>res.max THEN
      res.max=a(i)
    FI
    IF a(i)<res.min THEN
      res.min=a(i)
    FI
    res.sum==+a(i)
  OD
RETURN (res)

PROC Main()
  CARD ARRAY a=[123 5267 42 654 234 6531 4432]
  CARD minV,maxV,sumV
  Record rec
  Record POINTER p

  Put(125) PutE() ;clear screen 
  AllocInit(0)

  ArgumentsAsPointers(a,7,@minV,@maxV,@sumV)
  PrintE("Return multiple values by passing arguments as pointers:")
  PrintF("min=%U max=%U sum=%U%E%E",minV,maxV,sumV)

  ArgumentAsRecord(a,7,rec)
  PrintE("Return multiple values by passing argument as pointer to a record:")
  PrintF("min=%U max=%U sum=%U%E%E",rec.min,rec.max,rec.sum)

  p=ResultAsRecord(a,7)
  PrintE("Return multiple values by returning a pointer to a record:")
  PrintF("min=%U max=%U sum=%U%E",p.min,p.max,p.sum)

  Free(p,RECORD_SIZE)
RETURN
Output:

Screenshot from Atari 8-bit computer

Return multiple values by passing arguments as pointers:
min=42 max=6531 sum=17283

Return multiple values by passing argument as pointer to a record:
min=42 max=6531 sum=17283

Return multiple values by returning a pointer to a record:
min=42 max=6531 sum=17283

Ada

Ada functions can only return one type. That type could be an array or record holding multiple values, but the usual method for returning several values is using a procedure with 'out' parameters. By default, all parameters are 'in', but can also be 'out', 'in out' and 'access'. Writing to an 'out' parameter simply changes the value of the variable passed to the procedure.

with Ada.Text_IO; use Ada.Text_IO;
procedure MultiReturn is
   procedure SumAndDiff (x, y : Integer; sum, diff : out Integer) is begin
      sum := x + y;
      diff := x - y;
   end SumAndDiff;
   inta : Integer := 5;
   intb : Integer := 3;
   thesum, thediff : Integer;
begin
   SumAndDiff (inta, intb, thesum, thediff);
   Put_Line ("Sum:" & Integer'Image (thesum));
   Put_Line ("Diff:" & Integer'Image (thediff));
end MultiReturn;
Output:
Sum: 8
Diff: 2

Agena

Agena allows functions to return multiple values.
Tested with Agena 2.9.5 Win32

# define a function returning three values
mv := proc() is
    return 1, 2, "three"
end ; # mv

scope # test the mv() proc
    local a, b, c := mv();
    print( c, b, a )
epocs

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.6.win32

Procedures in Algol 68 can only return one value, so to return multiple values, a structure (or array if all the values have the same mode) can be used.

# example mode for returning multiple values from a procedure #
MODE PAIR = STRUCT( STRING name, INT value );

# procedure returning multiple values via a structure #
PROC get pair = ( INT a )PAIR:
    CASE a
    IN #1#    ( "H",  0 )
    ,  #2#    ( "He", 1 )
    ,  #3#    ( "Li", 3 )
    OUT       ( "?",  a )
    ESAC
;

main: (
    # use the result as a whole #
    print( ( get pair( 3 ), newline ) );
    # access the components separately #
    print( ( name OF get pair( 1 ), value OF get pair( 2 ), newline ) )
)
Output:
Li         +3
H         +1

ALGOL W

Algol W procedures can't return arrays but records can be used to return multiple values.

begin
    % example using a record type to return multiple values from a procedure %
    record Element ( string(2) symbol; integer atomicNumber );
    reference(Element) procedure getElement( integer value n ) ;
    begin
        Element( if      n < 1 then   "?<"
                 else if n > 3 then   "?>"
                 else case n of ( %1% "H"
                                , %2% "He"
                                , %3% "Li"
                                )
               , n
               )
    end getElement ;
    % test the procedure %
    begin
        reference(Element) elementData;
        for n := 0 until 4 do begin
            elementData := getElement(n);
            write( s_w := 0, i_w := 1
                 , atomicNumber(elementData)
                 , " "
                 , symbol(elementData)
                 );
        end
    end

end.

Amazing Hopper

Hopper posee una pila de trabajo de alcance global; luego, los datos pueden ser puestos ahí y accedidos desde cualquier parte del programa.

#include <basico.h>

#proto foo(_X_,_Y_)

algoritmo

    _foo(10,1), decimales '13', imprimir

    números(v,w,x,y,z, suma)
    _foo(0.25,0) ---retener(5)--- sumar todo,
    mover a 'v,w,x,y,z,suma'
    
    imprimir(NL,v,NL, w,NL, x,NL, y,NL, z,NL,NL,suma,NL)

terminar

subrutinas

foo(c,sw)
    #(c*10),        solo si( sw, NL)
    #(c/100),       solo si( sw, NL)
    #(0.25^c),      solo si( sw, convertir a notación; NL)
    #(2-(sqrt(c))), solo si( sw, NL)
    cuando ' #(!(sw)) '{
        #( ((c^c)^c)^c )
    }
retornar
Output:
100.0000000000000
0.1000000000000
9.536743e-07
-1.1622776601684

2.5000000000000
0.0025000000000
0.7071067811865
1.5000000000000
0.9785720620877

5.6881788432742

ARM Assembly

When programming without any rules governing the way you write functions, a function's "return value" is nothing more than the register state upon exit. However, the AAPCS calling convention dictates that the R0 register is used to store a function's return value. (If the return value is larger than 32 bits, the registers R1-R3 can also be used.) Following this standard is necessary for human-written assembly code to properly interface with code written by a C compiler.

This function takes two numbers in R0 and R1, and returns their sum in R0 and their difference in R1.

foo:
MOV R2,R0
MOV R3,R1
ADD R0,R2,R3
SUB R1,R2,R3
BX LR

Arturo

addsub: function [x y]->
    @[x+y x-y]

a: 33
b: 12

result: addsub a b

print [a "+" b "=" result\0]
print [a "-" b "=" result\1]
Output:
33 + 12 = 45 
33 - 12 = 21

ATS

Every function returns one value. The conventional way to return multiple values is to return a tuple.

//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)

fun addsub
(
  x: int, y: int
) : (int, int) = (x+y, x-y)

(* ****** ****** *)

implement
main0 () = let
  val (sum, diff) = addsub (33, 12)
in
  println! ("33 + 12 = ", sum);
  println! ("33 - 12 = ", diff);
end (* end of [main0] *)

AutoHotkey

Works with: AutoHotkey_L

Functions may return one value. The conventional way to return multiple values is to bundle them into an Array.

addsub(x, y) {
  return [x + y, x - y]
}

AutoIt

Return an array.

Func _AddSub($iX, $iY)
Local $aReturn[2]
$aReturn[0] = $iX + $iY
$aReturn[1] = $iX - $iY
Return $aReturn
EndFunc

BASIC

ANSI BASIC

Works with: Decimal BASIC

The most straightforward way of returning multiple values is to specify them as parameters.

100 DECLARE EXTERNAL SUB sumdiff
110 !
120 CALL sumdiff(5, 3, sum, diff)
130 PRINT "Sum is "; sum
140 PRINT "Difference is "; diff
150 END
160 !
170 EXTERNAL SUB sumdiff(a, b, c, d)
180 LET c = a + b
190 LET d = a - b
200 END SUB
Output:
Sum is  8 
Difference is  2 

BaCon

BaCon can return homogeneous dynamic arrays, or RECORD data holding heterogeneous types.

' Return multiple values
RECORD multi
    LOCAL num
    LOCAL s$[2]
END RECORD

FUNCTION f(n) TYPE multi_type
    LOCAL r = { 0 } TYPE multi_type
    r.num = n
    r.s$[0] = "Hitchhiker's Guide"
    r.s$[1] = "Douglas Adams"
    RETURN r
END FUNCTION

DECLARE rec TYPE multi_type
rec = f(42)
PRINT rec.num
PRINT rec.s$[0]
PRINT rec.s$[1]
Output:
prompt$ ./return-multiple
42
Hitchhiker's Guide
Douglas Adams

BBC BASIC

The most straightforward way of returning multiple values is to specify them as RETURNed parameters.

      PROCsumdiff(5, 3, sum, diff)
      PRINT "Sum is " ; sum
      PRINT "Difference is " ; diff
      END
      
      DEF PROCsumdiff(a, b, RETURN c, RETURN d)
      c = a + b
      d = a - b
      ENDPROC

IS-BASIC

100 NUMERIC SUM,DIFF
110 CALL SUMDIFF(5,3,SUM,DIFF)
120 PRINT "Sum is";SUM:PRINT "Difference is";DIFF
130 END 
140 DEF SUMDIFF(A,B,REF C,REF D)
150   LET C=A+B:LET D=A-B
160 END DEF

uBasic/4tH

Translation of: Forth

uBasic/4tH shares many features with Forth - like a stack. Parameters of functions and procedures are passed through this stack, so there is no difference between pushing the values on the stack or passing them as function parameters. Return values are passed by the stack as well, so if we push additional values before calling RETURN we can retrieve them using POP().

a = FUNC (_MulDiv (33, 11))
b = Pop()

Print "a * b = ";a, "a / b = ";b

Push 33, 11 : Proc _MulDiv
a = Pop() : b = Pop()

Print "a * b = ";a, "a / b = ";b
End

_MulDiv
  Param (2)

  Push a@ / b@
Return (a@ * b@)
Output:
a * b = 363     a / b = 3
a * b = 363     a / b = 3

0 OK, 0:226 

Binary Lambda Calculus

In the lambda calculus, one can return a tuple, which when applied to a function f, applies f to all the tuple elements. For example, <A,B,C> is \f.f A B C. Alternatively, one can use continuation-passing-style (cps), in which the function f is not applied the tuple return value, but instead is passed as an extra initial argument, and then the function can return f applied to the multiple values.

BQN

BQN is an array language, and hence arrays are the method of returning multiple values from a function. These values can then be separated with pattern matching.

   Func{𝕩+1, 𝕩÷2, 𝕩×3}
(function block)
   abcFunc 3
 4 1.5 9 
   a
4
   b
1.5
   c
9

Bracmat

Translation of: Haskell

Every function returns one value. The conventional way to return multiple values is to return a tuple.

(addsub=x y.!arg:(?x.?y)&(!x+!y.!x+-1*!y));

You can use pattern matching to extract the components:

( addsub$(33.12):(?sum.?difference)
& out$("33 + 12 = " !sum)
& out$("33 - 12 = " !difference)
);
Output:
33 + 12 =  45
33 - 12 =  21

C

C has structures which can hold multiple data elements of varying types.

#include<stdio.h>

typedef struct{
	int integer;
	float decimal;
	char letter;
	char string[100];
	double bigDecimal;
}Composite;

Composite example()
{
	Composite C = {1, 2.3, 'a', "Hello World", 45.678};
	return C;
}


int main()
{
	Composite C = example();

	printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);

	return 0;
}
Output:
Values from a function returning a structure : { 1, 2.300000, a, Hello World, 45.678000}

C99 and above also allow structure literals to refer to the name, rather than position, of the element to be initialized:

#include <stdio.h>

typedef struct {
    char *first, *last;
} Name;

Name whatsMyName() {
    return (Name) {
        .first = "James",
        .last = "Bond",
    };
}

int main() {
    Name me = whatsMyName();
    printf("The name's %s. %s %s.\n", me.last, me.first, me.last);
    return 0;
}
Output:
The name's Bond. James Bond.

C#

The preferred way to return multiple values in C# is to use "out" parameters on the method. This can be in addition to the value returned by the method.

using System;
using System.Collections.Generic;
using System.Linq;

class ReturnMultipleValues
{
    static void Main()
    {
        var values = new[] { 4, 51, 1, -3, 3, 6, 8, 26, 2, 4 };
        int max, min;
        MinMaxNum(values, out max, out min);

        Console.WriteLine("Min: {0}\nMax: {1}", min, max);
    }

    static void MinMaxNum(IEnumerable<int> nums, out int max, out int min)
    {
        var sortedNums = nums.OrderBy(num => num).ToArray();
        max = sortedNums.Last();
        min = sortedNums.First();
    }
}
Output:
Min: -3
Max: 51

C++

Since C++11, the C++-standard-library includes tuples, as well as an easy way to destructure them.

#include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>

std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
   const auto maximum = std::max_element(numbers, numbers + num);
   const auto minimum = std::min_element(numbers, numbers + num);
   return std::make_tuple(*minimum, *maximum) ;
}

int main( ) {
   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};
   int min{};
   int max{};
   std::tie(min, max) = minmax(numbers.data(), numbers.size());
   std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}
Output:
The smallest number is -10, the biggest 987!

Clipper

Every function returns one value. The conventional way to return multiple values is to bundle them into an array.

Function Addsub( x, y )
Return { x+y, x-y }

Clojure

Multiple values can be returned by packaging them in a vector. At receiving side, these arguments can be obtained individually by using destructuring.

(defn quot-rem [m n] [(quot m n) (rem m n)])

; The following prints 3 2.
(let [[q r] (quot-rem 11 3)]
  (println q)
  (println r))

In complex cases, it would make more sense to return a map, which can be destructed in a similar manner.

(defn quot-rem [m n]
  {:q (quot m n)
   :r (rem m n)})

; The following prints 3 2.
(let [{:keys [q r]} (quot-rem 11 3)]
  (println q)
  (println r))

CLU

% Returning multiple values (along with type parameterization)
% was actually invented with CLU.

% Do note that the procedure is actually returning multiple
% values; it's not returning a tuple and unpacking it. 
% That doesn't exist in CLU.

% For added CLU-ness, this function is fully general, requiring
% only that its arguments support addition and subtraction in any way

add_sub = proc [T,U,V,W: type] (a: T, b: U) returns (V, W)
          signals (overflow)
          where T has add: proctype (T,U) returns (V) signals (overflow),
                      sub: proctype (T,U) returns (W) signals (overflow)
    return (a+b, a-b) resignal overflow
end add_sub 


% And actually using it
start_up = proc ()
    add_sub_int = add_sub[int,int,int,int] % boring, but does what you'd expect
    po: stream := stream$primary_output()
    
    % returning two values from the function
    sum, diff: int := add_sub_int(33, 12)

    % print out both
    stream$putl(po, "33 + 12 = " || int$unparse(sum))
    stream$putl(po, "33 - 12 = " || int$unparse(diff))
end start_up
Output:
33 + 12 = 45
33 - 12 = 21

CMake

# Returns the first and last characters of string.
function(firstlast string first last)
  # f = first character.
  string(SUBSTRING "${string}" 0 1 f)

  # g = last character.
  string(LENGTH "${string}" length)
  math(EXPR index "${length} - 1")
  string(SUBSTRING "${string}" ${index} 1 g)

  # Return both characters.
  set("${first}" "${f}" PARENT_SCOPE)
  set("${last}" "${g}" PARENT_SCOPE)
endfunction(firstlast)

firstlast("Rosetta Code" begin end)
message(STATUS "begins with ${begin}, ends with ${end}")

COBOL

COBOL normally passes data BY REFERENCE, which is the default mode, effectively making the arguments modifiable.

User Defined Functions return a single argument, but that argument can be a group item.

Most large scale COBOL programs will attempt to keep from repeating itself, in terms of data layouts, using external copy books and the COBOL COPY statement. This example uses in source REPLACE to avoid copy books.

Works with: GnuCOBOL
       identification division.
       program-id. multiple-values.

       environment division.
       configuration section.
       repository.
           function multiples
           function all intrinsic.

       REPLACE ==:linked-items:== BY ==
       01 a usage binary-long.
       01 b pic x(10).
       01 c usage float-short.
       ==
       ==:record-item:== BY ==
       01 master.
          05 ma usage binary-long.
          05 mb pic x(10).
          05 mc usage float-short.
       ==.

       data division.
       working-storage section.
       :linked-items:

       :record-item:
       
       procedure division.
       sample-main.

       move 41 to a
       move "aaaaabbbbb" to b
       move function e to c

       display "Original: " a ", " b ", " c
       call "subprogram" using a b c
       display "Modified: " a ", " b ", " c
       
       move multiples() to master
       display "Multiple: " ma ", " mb ", " mc

       goback.
       end program multiple-values.

      *> subprogram
       identification division.
       program-id. subprogram.

       data division.
       linkage section.
       :linked-items:

       procedure division using a b c.
       add 1 to a
       inspect b converting "a" to "b"
       divide 2 into c
       goback.
       end program subprogram.

      *> multiples function
       identification division.
       function-id. multiples.

       data division.
       linkage section.
       :record-item:

       procedure division returning master.
       move 84 to ma
       move "multiple" to mb
       move function pi to mc
       goback.
       end function multiples.
Output:
prompt$ cobc -xj multiple-values.cob
Original: +0000000041, aaaaabbbbb, 2.7182817
Modified: +0000000042, bbbbbbbbbb, 1.3591409
Multiple: +0000000084, multiple  , 3.1415927

Common Lisp

Besides the obvious method of passing around a list, Common Lisp also allows a function to return multiple values. When citing the return values, if no interest is shown for multiple values, only the first (the primary return value) is used. Multiple values are not a data structure such as a tuple, list or array. They are a true mechanism for returning multiple values.

Returning a single value is accomplished by evaluating an expression (which itself yields a single value) at the end of a body of forms.

(defun return-three ()
  3)

The next possibility is that of returning no values at all. For this, the values function is used, with no arguments:

(defun return-nothing ()
  (values))

To combine the values of multiple expressions into a multi-value return, values is used with arguments. The following is from an interactive CLISP session. CLISP's listener shows multiple values separated by a semicolon:

[1]> (defun add-sub (x y) (values-list (list (+ x y) (- x y))))
ADD-SUB
[2]> (add-sub 4 2)    ; 6 (primary) and 2
6 ;
2
[3]> (add-sub 3 1)    ; 4 (primary) and 2
4 ;
2
[4]> (+ (add-sub 4 2) (add-sub 3 1))  ; 6 + 4
10
[5]> (multiple-value-call #'+ (add-sub 4 2) (add-sub 3 1)) ; 6+2+4+2
14

What happens if something tries to use the value of a form which returned (values)? In this case the behavior defaults to taking the value nil:

(car (values)) ;; no error: same as (car nil)

What if the values function is applied to some expressions which also yield multiple values, or which do not yield any values? The answer is that only the primary value is taken from each expression, or the value nil for any expression which did not yield a value:

(values (values 1 2 3) (values) 'a)

yields three values:

-> 1; NIL; A

This also means that values can be used to reduce a multiple value to a single value:

;; return exactly one value, no matter how many expr returns,
;; nil if expr returns no values
(values expr)

Multiple values are extracted in several ways.

1. Binding to variables:

(multiple-value-bind (dividend remainder) (truncate 16 3)
  ;; in this scope dividend is 5; remainder is 1
  )

2. Conversion to a list:

(multiple-value-list (truncate 16 3)) ;; yields (5 1)

3. Reification of multiple values as arguments to another function:

;; pass arguments 5 1 to +, resulting in 6:
(multiple-value-call #'+ (truncate 16 3))

4. Assignment to variables:

;; assign 5 to dividend, 1 to remainder:
(multiple-value-setq (dividend remainder) (truncate 16 1))

(values ...) syntax is treated as a multiple value place by setf and other operators, allowing the above to be expressed this way:

(setf (values dividend remainder) (truncate 16 1))

Cowgol

include "cowgol.coh";

# In Cowgol, subroutines can simply define multiple output parameters.
sub MinMax(arr: [uint8], len: intptr): (min: uint8, max: uint8) is
    min := 255;
    max := 0;
    while len > 0 loop
        len := len - 1;
        var cur := [arr];
        if min > cur then min := cur; end if;
        if max < cur then max := cur; end if; 
        arr := @next arr;
    end loop;
    
    # Values are also returned automatically.
end sub;

# Example of usage:
var nums: uint8[] := {23, 65, 33, 12, 95, 5, 32, 91, 135, 25, 8};
var least: uint8;
var most: uint8;

# Accept two output parameters from a function
(least, most) := MinMax(&nums[0], @sizeof nums);

print("Min: "); print_i8(least); print_nl();
print("Max: "); print_i8(most); print_nl();
Output:
Min: 5
Max: 135

D

import std.stdio, std.typecons, std.algorithm;


mixin template ret(string z) {
    mixin({
        string res;

        auto r = z.split(" = ");
        auto m = r[0].split(", ");
        auto s = m.join("_");

        res ~= "auto " ~ s ~ " = " ~ r[1] ~ ";";
        foreach(i, n; m){
            res ~= "auto " ~ n ~ " = " ~ s ~ "[" ~ i.to!string ~ "];\n";
        }
        return res;
    }());
}

auto addSub(T)(T x, T y) {
    return tuple(x + y, x - y);
}

void main() {
    mixin ret!q{ a, b = addSub(33, 12) };

    writefln("33 + 12 = %d\n33 - 12 = %d", a, b);
}
Output:
33 + 12 = 45
33 - 12 = 21

Dc

Define a divmod macro ~ which takes a b on the stack and returns a/b a%b.

[ S1 S2 l2 l1 / L2 L1 % ] s~
1337 42 l~ x f
Output:
35
31

Delphi/Pascal

Delphi functions return a single value, but var parameters of a function or procedure can be modified and act as return values.

program ReturnMultipleValues;

{$APPTYPE CONSOLE}

procedure GetTwoValues(var aParam1, aParam2: Integer);
begin
  aParam1 := 100;
  aParam2 := 200;
end;

var
  x, y: Integer;
begin
  GetTwoValues(x, y);
  Writeln(x);
  Writeln(y);
end.

Dyalect

A typical way to return multiple values in Dyalect is to use tuples:

func divRem(x, y) {
    (x / y, x % y)
}

Déjà Vu

function-returning-multiple-values:
     10 20

!print !print function-returning-multiple-values
Output:
10
20

EasyLang

proc addSubtract a b . sum diff .
   sum = a + b
   diff = a - b
.
addSubtract 7 5 sum diff
print "Sum: " & sum
print "Difference: " & diff
Output:
Sum: 12
Difference: 2

EchoLisp

One can return the result of the values function, or a list.

(define (plus-minus x y)
    (values (+ x y) (- x y)))
(plus-minus 3 4)
     7
     -1

(define (plus-minus x y)
    (list (+ x y) (- x y)))
(plus-minus 3 4)
     (7 -1)

ECL

MyFunc(INTEGER i1,INTEGER i2) := FUNCTION
  RetMod := MODULE
    EXPORT INTEGER Add  := i1 + i2;
    EXPORT INTEGER Prod := i1 * i2;
  END;
  RETURN RetMod;
END;

//Reference each return value separately:
MyFunc(3,4).Add;
MyFunc(3,4).Prod;

Eiffel

Every function returns one value. Multiple values can be returned in a tuple.

some_feature: TUPLE
	do
		Result := [1, 'j', "r"]
	end

Greater control over the type of return values can also be enforced by explicitly declaring the type of the generic parameters.

some_feature: TUPLE[INTEGER_32, CHARACTER_8, STRING_8]
	do
		--Result := [ ]			-- compile error	
		--Result := [1, "r", 'j']	-- also compile error	
		Result := [1, 'j', "r"]		-- okay
		Result := [1, 'j', "r", 1.23]	-- also okay
	end

Elena

ELENA 6.x :

import system'routines;
import extensions;
 
extension op
{
    MinMax(ref int minVal, ref int maxVal)
    {
        var ordered := self.ascendant();
 
        minVal := ordered.FirstMember;
        maxVal := ordered.LastMember
    }
}
 
public program()
{
    var values := new int[]{4, 51, 1, -3, 3, 6, 8, 26, 2, 4};
 
    values.MinMax(ref int min, ref int max);
 
    console.printLine("Min: ",min," Max: ",max)
}

Using Tuples syntax

import system'routines;
import extensions;
 
extension op
{
   ::(int, int) MinMax()
   {
      var ordered := self.ascendant();
 
      ^ (ordered.FirstMember, ordered.LastMember);
   }
}
 
public program()
{
   var values := new int[]{4, 51, 1, -3, 3, 6, 8, 26, 2, 4};
 
   (int min, int max) := values.MinMax();
 
   console.printLine("Min: ",min," Max: ",max)
}
Output:
Min: -3 Max: 51

Elixir

Elixir returns in the tuple form when returning more than one value.

defmodule RC do
  def addsub(a, b) do
    {a+b, a-b}
  end
end

{add, sub} = RC.addsub(7, 4)
IO.puts "Add: #{add},\tSub: #{sub}"
Output:
Add: 11,        Sub: 3

Erlang

% Put this code in return_multi.erl and run it as "escript return_multi.erl"

-module(return_multi).

main(_) ->
        {C, D, E} = multiply(3, 4),
        io:format("~p ~p ~p~n", [C, D, E]).

multiply(A, B) ->
        {A * B, A + B, A - B}.
Output:
12 7 -1

ERRE

FUNCTIONs in ERRE language return always a single value, but PROCEDUREs can return multiple values defining a parameter output list in procedure declaration using '->' separator.

PROGRAM RETURN_VALUES

PROCEDURE SUM_DIFF(A,B->C,D)
   C=A+B
   D=A-B
END PROCEDURE

BEGIN
   SUM_DIFF(5,3->SUM,DIFF)
   PRINT("Sum is";SUM)
   PRINT("Difference is";DIFF)
END PROGRAM

Euler

Euler procedures can return a list (Euler's only data structure), this is used here to return three values from the getMV procedure.
Procedures are defined by enclosing their text between ` and '. They can then be assigned to a variable for later use.
Lists are constructed by placing the values between ( and ). Once assigned to a variable, the list can be subscripted to access the individual elements (which can themselves be lists).

begin
    new mv; new getMV;

    getMV <- ` formal v; ( v, v * v, v * v * v ) ';

    mv <- getMV( 3 );

    out mv[ 1 ];
    out mv[ 2 ];
    out mv[ 3 ]
end $

Euphoria

Any Euphoria object can be returned. A sequence of objects can be returned, made from multiple data types as in this example.

include std\console.e --only for any_key, to help make running this program easy on windows GUI

integer aWholeNumber = 1
atom aFloat = 1.999999
sequence aSequence = {3, 4}
sequence result = {} --empty initialized sequence

function addmultret(integer first, atom second, sequence third)--takes three kinds of input, adds them all into one element of the.. 
    return (first + second + third[1]) + third[2] & (first * second * third[1]) * third[2] --..output sequence and multiplies them into..
end function --..the second element

result = addmultret(aWholeNumber, aFloat, aSequence) --call function, assign what it gets into result - {9.999999, 23.999988}
? result
any_key()
Output:
{9.999999,23.999988}
Press Any Key to continue...

F#

A function always returns exactly one value. To return multiple results, they are typically packed into a tuple:

let addSub x y = x + y, x - y

let sum, diff = addSub 33 12
printfn "33 + 12 = %d" sum
printfn "33 - 12 = %d" diff

Output parameters from .NET APIs are automatically converted to tuples by the compiler. It is also possible to use output parameters explicitly with the byref keyword, but this is rarely necessary.

Factor

With stack-oriented languages like Factor, a function returns multiple values by pushing them on the data stack. For example, this word */ pushes both x*y and x/y.

USING: io kernel math prettyprint ;
IN: script

: */ ( x y -- x*y x/y )
    [ * ] [ / ] 2bi ;

15 3 */

[ "15 * 3 = " write . ]
[ "15 / 3 = " write . ] bi*

Its stack effect declares that */ always returns 2 values. To return a variable number of values, a word must bundle those values into a sequence (perhaps an array or vector). For example, factors (defined in math.primes.factors and demonstrated at Prime decomposition#Factor) returns a sequence of prime factors.

FALSE

[\$@$@*@@/]f: { in: a b, out: a*b a/b }
6 2f;! .' ,.   { 3 12 }

Forth

It is natural to return multiple values on the parameter stack. Many built-in operators and functions do so as well (/mod, open-file, etc.).

: muldiv ( a b -- a*b a/b )
  2dup / >r * r> ;

Fortran

Translation of: Haskell
module multiple_values
implicit none
type res
  integer :: p, m
end type

contains

function addsub(x,y) result(r)
  integer :: x, y
  type(res) :: r 
  r%p = x+y
  r%m = x-y
end function
end module

program main
  use multiple_values 
  print *, addsub(33, 22)
end program

FreeBASIC

' FB 1.05.0 Win64

' One way to return multiple values is to use ByRef parameters for the additional one(s)
Function tryOpenFile (fileName As String, ByRef fileNumber As Integer) As Boolean
   Dim result As Integer 
   fileNumber = FreeFile
   result = Open(fileName For Input As # fileNumber)
   If result <> 0 Then
     fileNumber = 0
     Return False
   Else
     Return True
   End If
End Function

Dim fn As Integer
Var b = tryOpenFile("xxx.zyz", fn) '' this file doesn't exist
Print b, fn
b = tryOpenFile("input.txt", fn) '' this file does exist
Print b, fn
Close # fn

' Another way is to use a user defined type

Type FileOpenInfo
  opened As Boolean
  fn As Integer
End Type

Function tryOpenFile2(fileName As String) As FileOpenInfo
   Dim foi As FileOpenInfo 
   foi.fn = FreeFile
   Dim result As Integer
   result = Open(fileName For Input As # foi.fn)   
   If  result <> 0 Then
     foi.fn = 0
     foi.opened = False
   Else
     foi.Opened = True
   End If
   Return foi
End Function

Print
Var foi = tryOpenFile2("xxx.zyz") 
Print foi.opened, foi.fn
foi = tryOpenFile2("input.txt")
Print foi.opened, foi.fn
Close # foi.fn

Print
Print "Press any key to quit"
Sleep
Output:
false          0
true           1

false          0
true           1

Frink

The most common way of returning multiple values from a function is to return them as an array, which can be disassembled and set into individual variables on return.

divMod[a, b] := [a div b, a mod b]

[num, remainder] = divMod[10, 3]

FunL

Translation of: Scala
def addsub( x, y ) = (x + y, x - y)

val (sum, difference) = addsub( 33, 12 )

println( sum, difference, addsub(33, 12) )
Output:
45, 21, (45, 21)

FutureBasic

FutureBasic offers several ways to return multiple values from a function: by passing pointers to multiple values in and out of functions; global records (structures); global containers (imagine a global bit bucket that can hold up to 2GBs of data); and global arrays of either the standard kind, or of FB's dynamic arrays.

Here is an example of returning multiple values using pointers:

local fn ReturnMultipleValues( strIn as Str255, strOut as ^Str255, letterCount as ^long )
  Str255 s
  
  // Test if incoming string is empty, and exit function if it is
  if strIn[0] == 0 then exit fn
  
  // Prepend this string to incoming string and return it
  s = "Here is your original string: "
  strOut.nil$ = s + strIn
  
  // Get length of combined string and return it
  // Note: In FutureBasic string[0] is interchangeable with Len(string)
  letterCount.nil& = strIn[0] + s[0]
end fn

Str255 outStr
long   outCount

fn ReturnMultipleValues( "Hello, World!", @outStr, @outCount )
print outStr; ". The combined strings have ";outCount; " letters in them."

HandleEvents

Output:

Here is your original string: Hello, World!. The combined strings have 43 letters in them.

Another way to pass multiple values from a function is with records (AKA structures):

// Elements in global array
_maxDim = 3

begin record Addresses
  Str63 name
  Str15 phone
  long zip
end record

begin globals
Addresses gAddressData(_maxDim)
end globals

local fn FillRecord( array(_maxDim) as Addresses )
  array.name(0) = "John Doe"
  array.name(1) = "Mary Jones"
  array.name(2) = "Bill Smith"
  
  array.phone(0) = "555-359-4411"
  array.phone(1) = "555-111-2211"
  array.phone(2) = "555-769-8071"
  
  array.zip(0) = 12543
  array.zip(1) = 67891
  array.zip(2) = 54321
end fn

// Pass address of global array to fill it
fn FillRecord( gAddressData(0) )

short i
for i = 0 to 2
  print gAddressData.name(i); ", ";
  print gAddressData.phone(i); ", Zip:";
  print gAddressData.zip(i)
next

HandleEvents

Output:

John Doe, 555-359-4411, Zip: 12543
Mary Jones, 555-111-2211, Zip: 67891
Bill Smith, 555-769-8071, Zip: 54321

You can also use global arrays to return multiple values from a function as in this example:

// Elements in global array
_maxDim = 3

begin globals
Str31  gAddressArray(_maxDim, _maxDim)
end globals

local fn FillRecord( array(_maxDim, _maxDim) as Str31 )
array( 0, 0 ) = "John Doe"
array( 1, 0 ) = "Mary Jones"
array( 2, 0 ) = "Bill Smith"

array( 0, 1 ) = "555-359-4411"
array( 1, 1 ) = "555-111-2211"
array( 2, 1 ) = "555-769-8071"

array( 0, 2 ) = "12543"
array( 1, 2 ) = "67891"
array( 2, 2 ) = "54321"
end fn

// Pass address of global array to fill it
fn FillRecord( gAddressArray( 0, 0 ) )

short i, j

for i = 0 to 2
j = 0
print gAddressArray(i, j    ); ", ";
print gAddressArray(i, j + 1); ", Zip: ";
print gAddressArray(i, j + 1)
next

HandleEvents

Output:

John Doe, 555-359-4411, Zip: 555-359-4411
Mary Jones, 555-111-2211, Zip: 555-111-2211
Bill Smith, 555-769-8071, Zip: 555-769-8071

Here is another example using FB's containers -- bit buckets that can hold up to 2GB of data contingent on system memory.

begin globals
// An FB container can hold up to 2GB of data, contingent on system memory
container gC1, gC2
end globals

local fn ReturnMultipleValuesInContainers
// Fill container with strings from inside function
gC1  = "Twas brillig, and the slithy toves" + chr$(13)
gC1 += "Did gyre and gimble in the wabe;"   + chr$(13)
gC1 += "All mimsy were the borogoves,"      + chr$(13)
gC1 += "And the mome raths outgrabe."       + chr$(13)
gC1 += "'Beware the Jabberwock, my son!"    + chr$(13)
gC1 += "The jaws that bite, the claws that catch!" + chr$(13)
gC1 += "Beware the Jubjub bird, and shun"   + chr$(13)
gC1 += "The frumious Bandersnatch!'"        + chr$(13)

// Fill another container with numbers
gC2  = "10254"+ chr$(13)
gC2 += "37"   + chr$(13)
gC2 += "64"   + chr$(13)
end fn

local fn ReturnNewMultipleValuesInContainers
gC1  = "Jabberwocky is gone, but here is some new text." + chr$(13)
gC2  = "1000000"
end fn

// Test to see containers are empty:
print gC1 : print gC2

// Fill the containers using a function
fn ReturnMultipleValuesInContainers

// Check results
print gC1 : print : print gC2

// Empty the containers
gC1 = "" : gC2 = ""

// Fill with another function
fn ReturnNewMultipleValuesInContainers

// Check the new results
print gC1 : print gC2

HandleEvents

Output:


Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
'Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!'

10254
37
64

Jabberwocky is gone, but here is some new text.

1000000

Fōrmulæ

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 —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solution

Every function returns one value. The conventional way to return multiple values is to return a list.

In the following example, the function returns the sum and product of two given numbers.

Go

Functions can return multiple values in Go:

func addsub(x, y int) (int, int) {
  return x + y, x - y
}

Or equivalently using named return style:

func addsub(x, y int) (sum, difference int) {
  sum = x + y
  difference = x - y
  return
}

When a function returns multiple values, you must assign to a comma-separated list of targets:

sum, difference := addsub(33, 12)
fmt.Printf("33 + 12 = %d\n", sum)
fmt.Printf("33 - 12 = %d\n", difference)
package main

import (
	"fmt"
)

// Return multiple values using a function
func Pet(name, color string) (string, string) {
	color = "white"
	return name, color
}

// Change multiple global values using a function and a struct
type Beast struct {
	Cry, Play string
}

var Fluffy = Beast{"Meow", "Mice"}

func myBeast() {
	Fluffy.Cry = "Hiss"
	// Fluffy.Play = "Ball"
}

// Return multiple values using a function and an array
func Cat(newCat []string) []string {
	newCat = append(newCat, "Milk")
	return newCat
}

// Return multiple values using a method and a struct
type Tabby struct {
	Sleep string
	Cry   string
}

func (myTab Tabby) Puss() (string, string) {
	myTab.Sleep = "Zzzz"
	myTab.Cry = "Purr"
	return myTab.Sleep, myTab.Cry
}

func main() {
	// Return multiple values using a function
	name, color := Pet("Shadow", "Black")
	fmt.Println(name, color) // prt Puss Black

	// Change multiple global values using a function and a struct
	// fmt.Println(Fluffy.Cry, Fluffy.Play) // prt Meow Mice
	myBeast()
	fmt.Println(Fluffy.Cry, Fluffy.Play) // prt Purr Ball

	// Return multiple values using a function and an array
	newCat := make([]string, 2)
	newCat[0] = "Ginger"
	newCat[1] = "Orange"
	myPuss := Cat(newCat)
	fmt.Println(myPuss[1], myPuss[2]) // prt Orange Milk

	// Return multiple values using a method and a struct
	myCat := Tabby{Sleep: "Snore", Cry: "Meow"}
	puss, poo := myCat.Puss()
	fmt.Println(puss, poo) // prt Kitty Cat
}

Groovy

In Groovy functions return one value. One way to return multiple ones is to use anonymous maps as a sort of tuple.

def addSub(x,y) {
 [
  sum: x+y,
  difference: x-y
 ]
}

Result:

addSub(10,12) 
 
["sum":22, "difference":-2]

And although Groovy functions only return one value, Groovy assignments of Iterable objects (lists, arrays, sets, etc.) can be distributed across multiple variables, like this:

def addSub2(x,y) {
  [ x+y , x-y ]
}

def (sum, diff) = addSub2(50, 5)
assert sum == 55
assert diff == 45

If there are fewer elements than variables, the leftover variables are assigned null. If there are more elements than variables, the last variable is assigned the collected remainder of the elements.

Harbour

Every function returns one value. The conventional way to return multiple values is to bundle them into an array.

FUNCTION Addsub( x, y )
   RETURN { x + y, x - y }

However, we can 'return' multiple individual values, that are produced/processed/altered inside a function, indirectly, passing parameters `by reference`.

For example:

PROCEDURE Main()
   LOCAL Street, City, Country
 
   IF GetAddress( @Street, @City, @Country )
       ? hb_StrFormat( "Adrress: %s, %s, %s", Street, City, Country )
      // output: Route 42, Android-Free Town, FOSSLAND
   ELSE
      ? "Cannot obtain address!"
   ENDIF
 
FUNCTION GetAddress( cS, cC, cCn)
   cS := "Route 42"
   cC := "Android-Free Town"
   cCn:= "FOSSLAND"
   RETURN .T.

Haskell

Every function returns one value. The conventional way to return multiple values is to return a tuple.

  addsub x y = (x + y, x - y)

You can use pattern matching to extract the components:

main = do
  let (sum, difference) = addsub 33 12
  putStrLn ("33 + 12 = " ++ show sum)
  putStrLn ("33 - 12 = " ++ show difference)

Icon and Unicon

Icon and Unicon values range from simple atomic values like integers and strings to structures like lists, tables, sets, records. The contents of structures are heterogeneous and any of them could be used to return multiple values all at once. Additionally, generators are supported that return multiple results one at a time as needed.

The following examples return 1, 2, 3 in different ways:

procedure retList() # returns as ordered list
return [1,2,3]
end

procedure retSet()             # returns as un-ordered list
insert(S := set(),3,1,2)  
return S
end

procedure retLazy()            # return as a generator
suspend 1|2|3
end

procedure retTable()           # return as a table
T := table()
T["A"] := 1
T["B"] := 2 
T["C"] := 3
return T
end

record retdata(a,b,c)

procedure retRecord()          # return as a record, least general method
return retdata(1,2,3)
end

J

To return multiple values in J, you return an array which contains multiple values. Since the only data type in J is array (this is an oversimplification, from some perspectives - but those issues are out of scope for this task), this is sort of like asking how to return only one value in another language.

   1 2+3 4
4 6

Java

Java does not have tuples, so the most idiomatic approach would be to create a nested or inner-class specific to your values.

Point getPoint() {
    return new Point(1, 2);
}

static class Point {
    int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

It is not recommended to return an Object array from a method.
This will require the receiving procedure a casting operation, possibly preceded by an instanceof conditional check.

If you're using objects that are not known until runtime, use Java Generics.

Values<String, OutputStream> getValues() {
    return new Values<>("Rosetta Code", System.out);
}

static class Values<X, Y> {
    X x;
    Y y;

    public Values(X x, Y y) {
        this.x = x;
        this.y = y;
    }
}


Or, an alternate demonstration

Translation of: NetRexx
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

// =============================================================================
public class RReturnMultipleVals {
  public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
  public static final Long   K_1024   = 1024L;
  public static final String L        = "L";
  public static final String R        = "R";

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  public static void main(String[] args) throws NumberFormatException{
    Long nv_;
    String sv_;
    switch (args.length) {
      case 0:
        nv_ = K_1024;
        sv_ = K_lipsum;
        break;
      case 1:
        nv_ = Long.parseLong(args[0]);
        sv_ = K_lipsum;
        break;
      case 2:
        nv_ = Long.parseLong(args[0]);
        sv_ = args[1];
        break;
      default:
        nv_ = Long.parseLong(args[0]);
        sv_ = args[1];
        for (int ix = 2; ix < args.length; ++ix) {
          sv_ = sv_ + " " + args[ix];
        }
        break;
    }

    RReturnMultipleVals lcl = new RReturnMultipleVals();

    Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); // values returned in a bespoke object
    System.out.println("Results extracted from a composite object:");
    System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal());

    List<Object> rvl = lcl.getPairFromList(nv_, sv_); // values returned in a Java Collection object
    System.out.println("Results extracted from a Java Colections \"List\" object:");
    System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1));

    Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); // values returned in a Java Collection object
    System.out.println("Results extracted from a Java Colections \"Map\" object:");
    System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R));
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // Return a bespoke object.
  // Permits any number and type of value to be returned
  public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) {
    return new Pair<T, U>(vl_, vr_);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // Exploit Java Collections classes to assemble a collection of results.
  // This example uses java.util.List
  public List<Object> getPairFromList(Object nv_, Object sv_) {
    List<Object> rset = new ArrayList<Object>();
    rset.add(nv_);
    rset.add(sv_);
    return rset;
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // Exploit Java Collections classes to assemble a collection of results.
  // This example uses java.util.Map
  public Map<String, Object> getPairFromMap(Object nv_, Object sv_) {
    Map<String, Object> rset = new HashMap<String, Object>();
    rset.put(L, nv_);
    rset.put(R, sv_);
    return rset;
  }

  // ===========================================================================
  private static class Pair<L, R> {
    private L leftVal;
    private R rightVal;

    public Pair(L nv_, R sv_) {
      setLeftVal(nv_);
      setRightVal(sv_);
    }
    public void setLeftVal(L nv_) {
      leftVal = nv_;
    }
    public L getLeftVal() {
      return leftVal;
    }
    public void setRightVal(R sv_) {
      rightVal = sv_;
    }
    public R getRightVal() {
      return rightVal;
    }
  }
}

Otherwise

public class Values {
	private final Object[] objects;
	public Values(Object ... objects) {
		this.objects = objects;
	}
	public <T> T get(int i) {
		return (T) objects[i];
	}
	public Object[] get() {
		return objects;
	}
	
	// to test
	public static void main(String[] args) {
		Values v = getValues();
		int i = v.get(0);
		System.out.println(i);
		printValues(i, v.get(1));
		printValues(v.get());
	}
	private static Values getValues() {
		return new Values(1, 3.8, "text");
	}
	private static void printValues(int i, double d) {
		System.out.println(i + ", " + d);
	}
	private static void printValues(Object ... objects) {
		for (int i=0; i<objects.length; i+=1) System.out.print((i==0 ? "": ", ") + objects[i]);
		System.out.println();
	}
}
Output:
1
1, 3.8
1, 3.8, text

JavaScript

Javascript does not support multi-value bind until ECMAScript 6 is released (still a draft as of May 2015). The multi-value return is actually a destructured binding. Support may not be present yet in most implementations.

//returns array with three values
var arrBind = function () {
  return [1, 2, 3]; //return array of three items to assign
};

//returns object with three named values
var objBind = function () {
  return {foo: "abc", bar: "123", baz: "zzz"};
};

//keep all three values
var [a, b, c] = arrBind();//assigns a => 1, b => 2, c => 3
//skip a value
var [a, , c] = arrBind();//assigns a => 1, c => 3
//keep final values together as array
var [a, ...rest] = arrBind();//assigns a => 1, rest => [2, 3]


//same return name
var {foo, bar, baz} = objBind();//assigns foo => "abc", bar => "123", baz => "zzz"
//different return name (ignoring baz)
var {baz: foo, buz: bar} = objBind();//assigns baz => "abc", buz => "123"
//keep rest of values together as object
var {foo, ...rest} = objBind();//assigns foo => "abc, rest => {bar: "123", baz: "zzz"}

jq

jq supports streams of JSON values, so there are two main ways in which a function can return multiple values: as a stream, or as an array. Using the same example given for the Julia entry:

# To produce a stream:
def addsub(x; y): (x + y), (x - y);

# To produce an array:
def add_subtract(x; y): [ x+y, x-y ];

The builtin filter .[] streams its input if the input is an array, e.g. the expression [1,2] | .[] produces the stream:

 
1
2

Julia

function addsub(x, y)
  return x + y, x - y
end
julia> addsub(10,4)
(14,6)

Kotlin

Although Kotlin doesn't support tuples as such, it does have generic Pair and Triple types which can be used to return 2 or 3 values from a function. To return more values, a data class can be used. All of these types can be automatically destructured to separate named variables.

// version 1.0.6

/* implicitly returns a Pair<Int, Int>*/
fun minmax(ia: IntArray) = ia.min() to ia.max()

fun main(args: Array<String>) {
    val ia = intArrayOf(17, 88, 9, 33, 4, 987, -10, 2)
    val(min, max) = minmax(ia) // destructuring declaration
    println("The smallest number is $min")
    println("The largest  number is $max")
}
Output:
The smallest number is -10
The largest  number is 987

Lambdatalk

Lambdatalk can retun several values glued into conses or arrays.

{def foo
 {lambda {:n}
  {cons {- :n 1} {+ :n 1}}}}       // two values
-> foo

{foo 10}
-> (9 11)

{def bar 
 {lambda {:n}
  {A.new {- :n 1} :n {+ :n 1} }}}  // three values and more
-> bar

{bar 10}
-> [9,10,11]

Lasso

define multi_value() => {
	return (:'hello word',date)
}
// shows that single method call will return multiple values
// the two values returned are assigned in order to the vars x and y
local(x,y) = multi_value

'x: '+#x
'\ry: '+#y
Output:
x: hello word
y: 2013-11-06 01:03:47

Liberty BASIC

Using a space-delimited string to hold the array. LB functions return only one numeric or string value, so the function returns a string from which can be separated the two desired values.

data$ ="5 6 7 22 9 3 4 8 7 6 3 -5 2 1 8 9"

a$ =minMax$( data$)
print " Minimum was "; word$( a$, 1, " "); " & maximum was "; word$( a$, 2, " ")

end

function minMax$( i$)
min = 1E6
max =-1E6
i =1
do
    t$    =word$( i$, i, " ")
    if t$ ="" then exit do
    v     =val( t$)
    min   =min( min, v)
    max   =max( max, v)
    i =i +1
loop until 0
minMax$ =str$( min) +" " +str$( max)
end function
 Minimum was -5 & maximum was 22

Lily

No support for returning multiple values, but (similar to Scala), a Tuple can be returned.

define combine(a: Integer, b: String): Tuple[Integer, String]
{
  return <[a, b]>
}

The current version (0.17) has no support for destructuring Tuple assigns.

Lua

function addsub( a, b )
    return a+b, a-b
end

s, d = addsub( 7, 5 )
print( s, d )


M2000 Interpreter

Functions can be made in 5 ways: Normal, Lambda, Simple, Group which return value, Pointer to Group which return value. For every way we can return multiple values as tuple (in a mArray type of array). The (a,b)=funcA() is a way to define/assign values from tuple. So (a,b)=(1, 2) is the simple form. A return value from a function done using = as statement. This return isn't the last statement (isn't exit from function), so may we have multiple = as statements and the last one which we execute return the value. By default if we don't use the = statement based on function's suffix at name (at call) we get 0 or "". Functions can return any type of types. So the return type based on statement = (or the interpreter return 0 or "" based on name at call, where suffix $ means we return empty string, although later versions of language can return string/ make string variables without suffix $).

module Return_multiple_values{
	Print "Using a function"
	function twovalues(x) {
		="ok", x**2, x**3
	}
	// this is a sugar syntax to apply a tuple (mArray type) to variables
	// can be new variables or pre defined
	// if they are predifined then overflow may happen
	byte b
	// object a=(,)  // if a is an object we can't assign number
	(s, a,b)=twovalues(3)  // twovalues(30) raise overflow
	Print a=9, b=27, s="ok"
	c=twovalues(3)
	// need to use val$() because val() on string type is like a Val("1233")
	Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
	// we can pass by reference
	callbyref(&twovalues())
	sub callbyref(&a())
		local a, b, s as string
		(s, a,b)=a(3) 
		Print a=9, b=27, s="ok"
	end sub	
}
Return_multiple_values
// modules may change definitions like functions (but not subs and simple functions)
Module Return_multiple_values{
	// lambdas are first citizens, can be called as functions or used as variables/values
	Print "Using lambda function"
	twovalues=lambda (x) ->{
		="ok", x**2, x**3
	}
	byte b
	(s, a,b)=twovalues(3)  // twovalues(30) raise overflow
	Print a=9, b=27, s="ok"
	c=twovalues(3)
	Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
	callbyref(&twovalues())
	callbyValue(twovalues, 3)
	sub callbyref(&a())
		local a, b, s as string
		(s, a,b)=a(3) 
		Print a=9, b=27, s="ok"
	end sub
	sub callbyValue(g, v)
		local a, b, s as string
		(s, a,b)=g(v) 
		Print a=9, b=27, s="ok"
	end sub
}
Return_multiple_values
module Return_multiple_values{
	Print "Using simple function (static)"
	byte b
	(s, a,b)=@twovalues(3)  // twovalues(30) raise overflow
	Print a=9, b=27, s="ok"
	c=@twovalues(3)
	Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
	
	function twovalues(x)
		="ok", x**2, x**3
	end function
}
Return_multiple_values
module Return_multiple_values {
	//	a group may used as function too
	//	we can use fields to alter state
	//	we can't pass the object as function by reference
	//	but we can pass an object function
	//	group is a static object to this module
	//	in every call of this module, this object initialised
	//	when the group statement executed
	//	and destroyed at the end of execution without a call to remove destructor
	Print "Using a group as a function with a field"
	group twovalues {
		rep$="ok"
		function forRef(x) {
			=.rep$, x**2, x**3
		}
		value () { // ![] pass the stack of values to forRef function
			if empty then =this: exit
			=.forRef(![])  // or use =.rep$, x**2, x**3  and (x) at value
		}
		Set {
			Error "no object change allowed"
		}
	}
	byte b
	// object a=(,)  // if a is an object we can't assign number
	(s, a,b)=twovalues(3) 
	Print a=9, b=27, s="ok"
	twovalues.rep$="Yes"
	c=twovalues(3)
	// need to use val$() because val() on string type is like a Val("1233")
	Print c#val$(0)="Yes", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
	callbyref(&twovalues.forRef())
	callbyValue(twovalues, 3)
	sub callbyref(&a())
		local a, b, s as string
		(s, a,b)=a(3) 
		Print a=9, b=27, s="Yes"
	end sub
	sub callbyValue(g, v)
		local a, b, s as string
		(s, a,b)=g(v) 
		Print a=9, b=27, s="Yes"
	end sub
}
Return_multiple_values

module Return_multiple_values {
	Print "Using a pointer to group as a function with a field (group created by a Class)"
	class iTwovalues {
		string rep
		function forRef(x) {
			=.rep, x**2, x**3
		}
		value () { // ![] pass the stack of values to forRef function
			=.forRef(![])
		}
		Set {
			Error "no object change allowed"
		}
		// optional here, only to return the destriyed event (after the module exit from execution)
		remove {
			print .rep+" destroyed"
		}
	class:
		Module iTwovalues (.rep) {
		}
	}
	byte b
	// twovalues is a pointer to an object of general type Group
	twovalues->iTwovalues("ok")
	Print twovalues is type iTwovalues = true
	(s, a,b)=Eval(twovalues, 3)
	Print a=9, b=27, s="ok"
	twovalues=>rep="Yes"
	c=twovalues=>forRef(3) // better to call a function instead of use Eval()
	Print c#val$(0)="Yes", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
	for twovalues {
		// we have to use for object { } to use references to members of object
		callbyref(&.forRef())
	}
	// if we hide the next statement we will see Yes destroyed after return from this module (before "done")
	twovalues=pointer() // because twovalues is the last pointer to object, the object destroyed
	// we see now: Yes destroyed
	sub callbyref(&a())
		local a, b, s as string
		(s, a,b)=a(3) 
		Print a=9, b=27, s="Yes"
	end sub
}
Return_multiple_values
Print "Done"

Maple

> sumprod := ( a, b ) -> (a + b, a * b):
> sumprod( x, y );
                               x + y, x y

> sumprod( 2, 3 );
                                  5, 6

The parentheses are needed here only because of the use of arrow ("->") notation to define the procedure. One could do, instead:

sumprod := proc( a, b ) a + b, a * b end:

Mathematica/Wolfram Language

addsub [x_,y_]:= List [x+y,x-y]
addsub[4,2]
Output:
{6,2}

MATLAB / Octave

  function [a,b,c]=foo(d)
    a = 1-d; 
    b = 2+d; 
    c = a+b;
  end;  
  [x,y,z] = foo(5)
Output:
  > [x,y,z] = foo(5) 
  x = -4
  y =  7
  z =  3

Maxima

f(a, b) := [a * b, a + b]$

[u, v]: f(5, 6);
[30, 11]

Mercury

Mercury is a logic language. Its unification semantics permit any number of output parameters (the closest equivalent to return values). The sample code provided here centres on the addsub/4 predicate. The mode statement identifies the first two parameters as input parameters and the last two as output parameters, thus, in effect, returning two results. In this case the first output parameter returns the sum of the two inputs and the second output returns the difference of the two inputs.

addsub.m

:- module addsub.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list, string.

main(!IO) :-
    command_line_arguments(Args, !IO),
    filter_map(to_int, Args, CleanArgs),
    (length(CleanArgs, 2) ->
        X = det_index1(CleanArgs,1),
        Y = det_index1(CleanArgs,2),
        addsub(X, Y, S, D),
        format("%d + %d = %d\n%d - %d = %d\n", 
               [i(X), i(Y), i(S), i(X), i(Y), i(D)], !IO)
    ;
        write_string("Please pass two integers on the command line.\n", !IO)
    ).

:- pred addsub(int::in, int::in, int::out, int::out) is det.
addsub(X, Y, S, D) :-
    S = X + Y,
    D = X - Y.

:- end_module addsub.

Use and output

$ mmc addsub.m -E && ./addsub 100 999   
100 + 999 = 1099
100 - 999 = -899

Functions and tuples

Mercury is also a functional language, thus a function-based implementation is also possible. Functions in Mercury can only return a single value, but Mercury allows the use of arbitrary tuples containing multiple heterogeneous ad-hoc values which is, for all practical purposes, the same thing. The above code can be modified so that the definition of addsub/4 is now instead this function addsub/2:

:- func addsub(int, int) = {int, int}.
addsub(X, Y) = { X + Y, X - Y }.

Instead, now, of a predicate with two input and two output parameters of type int, addsub is a function that takes two int parameters and returns a tuple containing two int values. The call to addsub/4 in the above code is now replaced by this:

        {S, D} = addsub(X, Y),

All other code remains exactly the same as does the use and output of it.

Functions and type constructors

It should be noted that tuples as a construct are generally frowned upon in Mercury, relying as they do on structural type equivalence instead of nominative. The preferred approach is either to have multiple explicit output parameters on predicates or to have an explicit named type that covers the multi-return needs.

An example of this follows:

:- module addsub.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list, string.

:- type my_result ---> twin(int, int).

main(!IO) :-
    command_line_arguments(Args, !IO),
    filter_map(to_int, Args, CleanArgs),
    (length(CleanArgs, 2) ->
        X = det_index1(CleanArgs,1),
        Y = det_index1(CleanArgs,2),
        twin(S, D) = addsub(X, Y),
        format("%d + %d = %d\n%d - %d = %d\n",
               [i(X), i(Y), i(S), i(X), i(Y), i(D)], !IO)
    ;
        write_string("Please pass two integers on the command line.\n", !IO)
    ).

:- func addsub(int, int) = my_result.
addsub(X, Y) = twin(X + Y, X - Y).

:- end_module addsub.

Here the type my_result has been provided with a twin/2 constructor that accepts two int values. Use and output of the code is, again, exactly the same.

addsub/2 explicitly constructs a my_result value with the paired calculations and this is deconstructed in the call in the main predicate through unification. While the resulting code is slightly more verbose than the tuple-based version it is more strongly protected against type errors and is more explicit in its intent at the same time.

min

To return multiple values in min, simply leave them on the data stack.

Works with: min version 0.19.6
(over over / '* dip) :muldiv

MIPS Assembly

The registers $v0 and $v1 are intended for return values. Technically you can use any register you want, but the calling conventions use $v0 and $v1.

sum:
add $v0,$a0,$a1
jr ra
nop  ;branch delay slot

Nemerle

To return multiple values in Nemerle, package them into a tuple.

using System;
using System.Console;
using Nemerle.Assertions;

module MultReturn
{
    MinMax[T] (ls : list[T]) : T * T
      where T : IComparable
      requires ls.Length > 0 otherwise throw ArgumentException("An empty list has no extreme values.")
    {
        def greaterOf(a, b) { if (a.CompareTo(b) > 0) a else b }
        def lesserOf(a, b)  { if (a.CompareTo(b) < 0) a else b }
        
        (ls.FoldLeft(ls.Head, lesserOf), ls.FoldLeft(ls.Head, greaterOf)) // packing tuple
    }
    
    Main() : void
    {
        def nums = [1, 34, 12, -5, 4, 0];
        def (min, max) = MinMax(nums);                                   // unpacking tuple
        WriteLine($"Min of nums = $min; max of nums = $max");
    }
}

NetRexx

While a NetRexx method can only return a single "thing" to it's caller that "thing" can be an object which may contain a great deal of information. Typical return objects can be composite objects, Java Collection Class objects, NetRexx indexed strings etc.

Another common idiom inherited from REXX is the ability to collect the return data into a simple NetRexx string. Caller can then use the PARSE instruction to deconstruct the return value and assign the parts to separate variables.

/* NetRexx */
options replace format comments java crossref symbols nobinary

-- =============================================================================
class RReturnMultipleVals public
  properties constant
    L = 'L'
    R = 'R'
    K_lipsum = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
    K_1024 = 1024

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method RReturnMultipleVals() public
    return

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method main(args = String[]) public static
    arg = Rexx(args)
    parse arg nv_ sv_ .
    if \nv_.datatype('n') then nv_ = K_1024
    if sv_ = '' then sv_ = K_lipsum

    lcl = RReturnMultipleVals()

    rvr = lcl.getPair(nv_, sv_) -- multiple values returned as a string.  Use PARSE to extract values
    parse rvr val1 val2
    say 'Results extracted from a NetRexx string:'
    say val1',' val2
    say

    rvr = lcl.getPairFromRexx(nv_, sv_) -- values returned in a NetRexx indexed string
    say 'Results extracted from a NetRexx "indexed string":'
    say rvr[L]',' rvr[R]
    say

    rvp = lcl.getPairFromPair(nv_, sv_) -- values returned in a bespoke object
    say 'Results extracted from a composite object:'
    say rvp.getLeftVal',' rvp.getRightVal
    say

    rvl = lcl.getPairFromList(nv_, sv_) -- values returned in a Java Collection "List" object
    say 'Results extracted from a Java Colections "List" object:'
    say rvl.get(0)',' rvl.get(1)
    say

    rvm = lcl.getPairFromMap(nv_, sv_) -- values returned in a Java Collection "Map" object
    say 'Results extracted from a Java Colections "Map" object:'
    say rvm.get(L)',' rvm.get(R)
    say

    return

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  -- returns the values in a NetRexx string.
  --  Caller can the power of PARSE to extract the results
  method getPair(nv_, sv_) public returns Rexx
    return nv_ sv_

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  -- Return the values as members of a NetRexx indexed string
  method getPairFromRexx(nv_, sv_) public returns Rexx
    rval = ''
    rval[L] = nv_
    rval[R] = sv_
    return rval

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  -- Return a bespoke object.
  -- Permits any number and type of value to be returned
  method getPairFromPair(nv_, sv_) public returns RReturnMultipleVals.Pair
    rset = RReturnMultipleVals.Pair(nv_, sv_)
    return rset

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  -- Exploit Java Collections classes to assemble a collection of results.
  -- This example uses java.util.List
  method getPairFromList(nv_, sv_) public returns java.util.List
    rset = ArrayList()
    rset.add(nv_)
    rset.add(sv_)
    return rset

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  -- This example uses java.util.Map
  method getPairFromMap(nv_, sv_) public returns java.util.Map
    rset = HashMap()
    rset.put(L, nv_)
    rset.put(R, sv_)
    return rset

-- =============================================================================
class RReturnMultipleVals.Pair dependent

  properties indirect
    leftVal
    rightVal

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method Pair(nv_ = parent.K_1024, sv_ = parent.K_lipsum) public
    setLeftVal(nv_)
    setRightVal(sv_)
    return

Nim

Every function returns one value. We can return a tuple instead:

proc addsub(x, y: int): (int, int) =
  (x + y, x - y)

var (a, b) = addsub(12, 15)

Or manipulate the parameters directly:

proc addsub(x, y: int; a, b: var int) =
  a = x + y
  b = x - y

var a, b: int
addsub(12, 15, a, b)

Objeck

Easiest way to return multiple values is to use in/out objects. The language also supports returning collections.

class Program {
  function : Main(args : String[]) ~ Nil {
    a := IntHolder->New(3); b := IntHolder->New(7);
    Addon(a,b);
    a->Get()->PrintLine(); b->Get()->PrintLine();
  }
  
  function : Addon(a : IntHolder, b : IntHolder) ~ Nil {
    a->Set(a->Get() + 2); b->Set(b->Get() + 13);
  }
}

OCaml

Every function returns one value. The conventional way to return multiple values is to return a tuple.

let addsub x y =
  x + y, x - y

(Note that parentheses are not necessary for a tuple literal in OCaml.)

You can use pattern matching to extract the components:

let sum, difference = addsub 33 12 in
  Printf.printf "33 + 12 = %d\n" sum;
  Printf.printf "33 - 12 = %d\n" difference

Oforth

Oforth uses a data stack. A function return is everything left on the stack when the function ends, so a function can return as many objects as needed :

import: date

: returnFourValues 12 13 14 15 ;
: returnOneObject  [ 12, 13, 14, 15, [16, 17 ], Date now, 1.2, "abcd" ] ;

"Showing four values returned on the parameter stack:" println
returnFourValues .s clr

"\nShowing one object containing four values returned on the parameter stack:" println
returnOneObject .s clr

Output:

Showing four values returned on the parameter stack:
[1] (Integer) 15
[2] (Integer) 14
[3] (Integer) 13
[4] (Integer) 12

Showing one object containing four values returned on the parameter stack:
[1] (List) [12, 13, 14, 15, [16, 17], 2016-02-05 20:55:15,778, 1.2, abcd]

ooRexx

Functions and methods in ooRexx can only have a single return value, but that return value can be some sort of collection or other object that contains multiple values. For example, an array:

r = addsub(3, 4)
say r[1] r[2]

::routine addsub
  use arg x, y
  return .array~of(x + y, x - y)

Output:

7 -1

OxygenBasic

Demonstrated with vectors, using OOP and a pseudo-assign trick:

'============
class vector4
'============

float w,x,y,z

method values(float fw,fx,fy,fz)
this <= fw, fx, fy, fz
end method

method values(vector4 *v)
this <= v.w, v.x, v.y, v.z
end method

method values() as vector4
return this
end method

method ScaledValues(float fw,fx,fy,fz) as vector4
static vector4 v
v <= w*fw, x*fx, y*fy, z*fz
return v
end method

method ShowValues() as string
string cm=","
return w cm x cm y cm z
end method

end class

vector4 aa,bb

bb.values = 1,2,3,4

aa.values = bb.Values()

print aa.ShowValues() 'result 1,2,3,4

aa.values = bb.ScaledValues(100,100,-100,100)

print aa.ShowValues() 'result 100,200,-300,400

PARI/GP

The usual way to return multiple values is to put them in a vector:

foo(x)={
  [x^2, x^3]
};

Perl

Functions may return lists of values:

sub foo {
    my ($a, $b) = @_;
    return $a + $b, $a * $b;
}

Phix

Library: Phix/basics

Every function returns one value. You can return any number of items as elements of a sequence, and unpack them on receipt or not.

function stuff()
    return {"PI",'=',3.1415926535}
end function
{string what, integer op, atom val} = stuff()

PHP

Every function returns one value. The conventional way to return multiple values is to bundle them into an array.

function addsub($x, $y) {
  return array($x + $y, $x - $y);
}

You can use the list() construct to assign to multiple variables:

list($sum, $difference) = addsub(33, 12);
echo "33 + 12 = $sum\n";
echo "33 - 12 = $difference\n";

Additionally, if you specify a parameter as being a pointer, you do have the capacity to change that value. A built-in PHP example of this is preg_match() which returns a boolean value (to determine if a match was found or not), but which modifies the $matches parameter supplied to hold all the capture groups.

You can achieve this simply by adding the & before the desired parameter:

function multiples($param1, &$param2) {
	if ($param1 == 'bob') {
		$param2 = 'is your grandmother';
		return true;
	}
	
	return false;
}

echo 'First run: ' . multiples('joe', $y) . "\r\n";
echo "Param 2 from first run: '${y}'\r\n";

echo 'Second run: ' . multiples('bob', $y) . "\r\n";
echo "Param 2 from second run: '${y}'\r\n";

The above will yield the following output:

First run: 
Param 2 from first run: ''
Second run: 1
Param 2 from second run: 'is your grandmother'

Picat

Functions

Functions returns a single value. Multiple values must be collected in a list (or an array, map, set, structure).

main =>
  [A,B,C] = fun(10),
  println([A,B,C]).

fun(N) = [2*N-1,2*N,2*N+1].

Predicates

Sometimes it is not possible - or not convenient - to create a function that return values. In those cases a predicate is used and then some of the variables are considered output variables (and are usually placed last).

main => 
  pred(10, E,F,G),
  % ...

% A, B, and C are output variables
pred(N, A,B,C) =>
  A=2*N-1,
  B=2*N,
  C=2*N+1.

A variant of this is to use a structure (here $ret(A,B,C)) that collects the output values.

main =>   
  pred2(10, Ret),
  println(Ret),
  % or
  pred2(10,$ret(H,I,J)),
  println([H,I,J]).

% The structure $ret(A,B,C) contains the output values.
pred2(N, ret(A,B,C)) :-
  A=2*N-1,
  B=2*N,
  C=2*N+1.

Note: Sometimes the meaning of input/output variables are confusing, for example when a predicate can be used with multiple input/output modes, e.g. reversible predicates such as append/3 or member/2.


PicoLisp

A PicoLisp function returns a single value. For multiple return values, a cons pair or a list may be used.

(de addsub (X Y)
   (list (+ X Y) (- X Y)) )

Test:

: (addsub 4 2)
-> (6 2)
: (addsub 3 1)
-> (4 2)
: (+ (car (addsub 4 2)) (car (addsub 3 1)))
-> 10
: (sum + (addsub 4 2) (addsub 3 1))
-> 14

Pike

Multiple values are returned through an array. An array can be assigned to separate variables.

array(int) addsub(int x, int y)
{
    return ({ x+y, x-y });
}

[int z, int w] = addsub(5,4);

PL/I

Example 1 illustrates a function that returns an array:

   define structure 1 h,
                      2 a (10) float;
   declare i fixed binary;

sub: procedure (a, b) returns (type(h));
   declare (a, b) float;
   declare p type (h);
   do i = 1 to 10;
      p.a(i) = i;
   end;
   return (p);
end sub;

Example 2 illustrates a function that returns a general data structure:

   define structure 1 customer,
                      2 name,
                        3 surname character (20),
                        3 given_name character (10),
                      2 address,
                        3 street character (20),
                        3 suburb character (20),
                        3 zip fixed decimal (7);

sub2: procedure() returns (type(customer));
   declare c type (customer);
   get edit (c.surname, c.given_name) (L);
   get edit (c.street, c.suburb, c.zip) (L);
   return (c);
end sub2;

Example 3 illustrates the return of two values as a complex value:

comp: procedure(a, b) returns (complex);
   declare (a, b) float;

   return (complex(a, b) );
end comp;

Plain English

Since parameters are passed by reference by default in Plain English, returning values ends up being unnecessary in most cases. The only functions that actually return a value are Boolean functions, called deciders.

It is possible, however, to call an auxiliary routine to change fields in a record and:

  1. Concatenate these values, assigning the concatenated string to a new string (see code below);
  2. Write the concatenated string on the console; or
  3. As is done in C style, obtain the address of the record (a pointer) and save the pointer's value in a number for later manipulation.
The example record is a record with
  A number called first field,
  A string called second field,
  A flag called third field.
  
To run:
  Start up.
  Fill the example record.
  Write the example record on the console.
  Shut down.

To fill the example record:
  Put 123 into the example's record's first field.
  Put "Hello World!" into the example's record's second field.
  Set the example's record's third field.

To Write the example record on the console:
  Convert the example's example's record's first field to a string.
  Convert the example's example's record's third field to another string.
  Put the string then " " 
    then the example's record's second field 
    then " " then other string into a return string.
  Write the return string on the console.

When it is necessary to get the return value from a Win 32 API function, the syntax is as follows:

Call "dllname.dll" "FunctionNameHereIsCaseSensitive" returning a <type>.

Example:s

Call "gdi32.dll" "GetCurrentObject" with the printer canvas and 6 [obj_font] returning a handle.

Call "kernel32.dll" "SetFilePointer" with the file and 0 and 0 and 2 [file_end] returning a result number.

Call "kernel32.dll" "WriteFile" with the file and the buffer's first and the buffer's length and a number's whereabouts and 0 returning the result number.

Call "kernel32.dll" "HeapAlloc" with the heap pointer and 8 [heap_zero_memory] and the byte count returning the pointer.

Output:
123 Hello World! yes

PowerShell

function multiple-value ($a, $b) {
    [pscustomobject]@{
        a = $a
        b = $b
    }
}
$m =  multiple-value "value" 1
$m.a
$m.b

Output:

value
1

PureBasic

PureBasic's procedures return only a single value. The value needs to be a standard numeric type or string.

An array, map, or list can be used as a parameter to a procedure and in the process contain values to be returned as well. A pointer to memory or a structured variable may also be returned to reference multiple return values (requiring the memory to be manually freed afterwards).

;An array, map, or list can be used as a parameter to a procedure and in the
;process contain values to be returned as well.
Procedure example_1(x, y, Array r(1))  ;array r() will contain the return values
  Dim r(2) ;clear and resize the array
  r(0) = x + y  ;return these values in the array
  r(1) = x - y
  r(2) = x * y 
EndProcedure
  
;A pointer to memory or a structured variable may also be returned to reference
;multiple return values (requiring the memory to be manually freed afterwards).
Procedure example_2(x, y)
  Protected *result.POINT = AllocateMemory(SizeOf(POINT))
  *result\x = x
  *result\y = y

  ProcedureReturn *result ;*result points to a 'POINT' structure containing x and y
EndProcedure

If OpenConsole()
  Dim a(5)
  example_1(6, 5, a()) ;a() now contains {11, 1, 30}
  PrintN("Array returned with {" + Str(a(0)) + ", " + Str(a(1)) + ", " + Str(a(2)) + "}")
  
  Define *aPoint.POINT
  *aPoint = example_2(6, 5) ;*aPoint references structured memory containing {6, 5}
  
  PrintN("structured memory holds: (" + Str(*aPoint\x) + ", " + Str(*aPoint\y) + ")")
   FreeMemory(*aPoint) ;freememory
  
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf

Python

Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.

def addsub(x, y):
  return x + y, x - y

(Note that parentheses are not necessary for a tuple literal in Python.)

You can assign to a comma-separated list of targets:

sum, difference = addsub(33, 12)
print "33 + 12 = %s" % sum
print "33 - 12 = %s" % difference

There is no discernible difference between "returning multiple values" and returning a single tuple of multiple values. It is just a more pedantic/accurate statement of the mechanism employed.

Quackery

Words in Quackery take zero or more arguments from the data stack and leave zero or more results on the data stack.

We can demonstrate defining and using a word +*, which returns the sum and product of two numbers, in the Quackery shell.

Welcome to Quackery.

Enter "leave" to leave the shell.

/O> [ 2dup + unrot * ] is +* ( a b --> a+b a*b )
... 12 23 +*
... 

Stack: 35 276 

/O> 


R

The conventional way to return multiple values is to bundle them into a list.

addsub <- function(x, y) list(add=(x + y), sub=(x - y))

Racket

Racket has a defined function "values" that returns multiple values using continuations, a way it can be implemented is shown in "my-values"

#lang racket
(values 4 5)

(define (my-values . return-list)
  (call/cc
   (lambda (return)
     (apply return return-list))))

Raku

(formerly Perl 6)

Each function officially returns one value, but by returning a List or Seq you can transparently return a list of arbitrary (even infinite) size. The calling scope can destructure the list using assignment, if it so chooses:

sub addmul($a, $b) {
    $a + $b, $a * $b
}

my ($add, $mul) = addmul 3, 7;

In this example, the variable $add now holds the number 10, and $mul the number 21.

Raven

define multiReturn use $v
   $v each 

3 multiReturn
Output:
2
1
0

ReScript

let addsub = (x, y) => {
  (x + y, x - y)
}

let (sum, difference) = addsub(33, 12)

Js.log2("33 + 12 = ", sum)
Js.log2("33 - 12 = ", difference)

Retro

Functions take and return values via a stack. This makes returning multiple values easy.

: addSubtract ( xy-nm )
  2over - [ + ] dip ;

REXX

Strictly speaking, REXX only returns one value (or no values), but the value (a string) can comprise of
multiple "values" or substrings.

If the multiple values are separated by blanks   [or some other unique character(s) such as a comma,
semicolon, backslash, ···],   it's a very simple matter to parse the multiple-value string into the desired
substrings   (or values, if you will)   with REXX's handy-dandy   parse   statement.

/*REXX program shows and displays examples of multiple  RETURN  values  from a function.*/
numeric digits 70                                /*the default is:    NUMERIC DIGITS 9  */
parse arg a b .                                  /*obtain two numbers from command line.*/
if a=='' | a==","  then a= 82                    /*Not specified?  Then use the default.*/
if b=='' | b==","  then b= 20                    /* "      "         "   "   "     "    */
say '     a ='  a                                /*display the first number to the term.*/
say '     b ='  b                                /*   "     "  second   "    "  "    "  */
say copies('═', 50)                              /*display a separator line  "  "    "  */
z= arithmetics(a, b)                             /*call the function:   arithmetics     */
parse var z  abut sum diff rem div Idiv prod pow /*obtain the function's returned values*/
say '    || ='  abut                             /*display   abutment   to the terminal.*/
say '     + ='  sum                              /*   "        sum       "  "     "     */
say '     - ='  diff                             /*   "     difference   "  "     "     */
say '    // ='  rem                              /*   "     remainder    "  "     "     */
say '     / ='  div                              /*   "      quotient    "  "     "     */
say '     % ='  Idiv                             /*   "   int. quotient  "  "     "     */
say '     * ='  prod                             /*   "       product    "  "     "     */
say '    ** ='  pow                              /*   "        power     "  "     "     */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
arithmetics: procedure;  parse arg x,y;  return  x||y  x+y  x-y  x//y  x/y  x%y  x*y  x**y
output   when using the default inputs:
     a = 82
     b = 20
══════════════════════════════════════════════════
    || = 8220
     + = 102
     - = 62
    // = 2
     / = 4.1
     % = 4
     * = 1640
    ** = 188919613181312032574569023867244773376

Ring

Func AddSub x,y 
     Return [ x+y, x-y ]

RPL

The stack is where data are taken and then returned: stack size's the limit!

≪ + LAST - ≫ ‘ADDSUB’ STO
Input:
33 12 ADDSUB
Output:
2: 44
1: 20

Ruby

Every function returns one value. The conventional way to return multiple values is to bundle them into an Array.

Use an array literal:

def addsub(x, y)
  [x + y, x - y]
end

Or use return with 2 or more values:

def addsub(x, y)
  return x + y, x - y
end

(With at least 2 values, return makes a new Array. With 1 value, return passes the value, without making any Array. With 0 values, return passes nil.)

Assignment can split the Array into separate variables.

sum, difference = addsub(33, 12)
puts "33 + 12 = #{sum}"
puts "33 - 12 = #{difference}"

Run BASIC

Courtesy http://dkokenge.com/rbp
Gets the UTC time from the web

a$ = timeInfo$()
print " UTC:";word$(a$,1,"|")
print "Date:";word$(a$,2,"|")
print "Time:";word$(a$,3,"|")
wait
function timeInfo$()
utc$ = word$(word$(httpget$("http://tycho.usno.navy.mil/cgi-bin/timer.pl"),1,"UTC"),2,"<BR>") ' Universal time
d$   = date$()
t$  = time$()
timeInfo$ = utc$;"|";d$;"|";t$
end function

Rust

Rust supports ADT, thus function can return tuple.

fn multi_hello() -> (&'static str, i32) {
    ("Hello",42)
}

fn main() {
    let (str,num)=multi_hello();
    println!("{},{}",str,num);
}
Output:
Hello,42

Scala

Every function returns one value. The conventional way to return multiple values is to return a tuple.

def addSubMult(x: Int, y: Int) = (x + y, x - y, x * y)

A more detailed declaration would be:

def addSubMult(x: Int, y:Int) : (Int, Int, Int) = {
  ...
  (x + y, x - y, x * y)
}

You can use pattern matching to extract the components:

val (sum, difference) = addsub(33, 12)

Scala borrows this idea from ML, and generalizes it into extractors.

Scheme

Scheme can return multiple values using the values function, which uses continuations:

(define (addsub x y)
  (values (+ x y) (- x y)))

You can use the multiple values using the call-with-values function:

(call-with-values
  (lambda () (addsub 33 12))
  (lambda (sum difference)
    (display "33 + 12 = ") (display sum) (newline)
    (display "33 - 12 = ") (display difference) (newline)))

The syntax is kinda awkward. SRFI 8 introduces a receive construct to make this simpler:

(receive (sum difference) (addsub 33 12)
  ; in this scope you can use sum and difference
  (display "33 + 12 = ") (display sum) (newline)
  (display "33 - 12 = ") (display difference) (newline))

SRFI 11 introduces a let-values construct to make this simpler:

(let-values (((sum difference) (addsub 33 12)))
  ; in this scope you can use sum and difference
  (display "33 + 12 = ") (display sum) (newline)
  (display "33 - 12 = ") (display difference) (newline))

Seed7

Seed7 functions can only return one value. That value could be an array or record holding multiple values, but the usual method for returning several values is using a procedure with inout parameters:

$ include "seed7_05.s7i";

const proc: sumAndDiff (in integer: x, in integer: y, inout integer: sum, inout integer: diff) is func
  begin
    sum := x + y;
    diff := x - y;
 end func;

const proc: main is func
  local
    var integer: sum is 0;
    var integer: diff is 0;
  begin
    sumAndDiff(5, 3, sum, diff);
    writeln("Sum: " <& sum);
    writeln("Diff: " <& diff);
  end func;
Output:
Sum: 8
Diff: 2

SenseTalk

You can return multiple values in SenseTalk by returning a list, which can be assigned to multiple variables.

set [quotient,remainder] to quotientAndRemainder(13,4)

put !"The quotient of 13 ÷ 4 is: [[quotient]] with remainder: [[remainder]]"

to handle quotientAndRemainder of num, divisor
	return [num div divisor, num rem divisor]
end quotientAndRemainder
Output:
The quotient of 13 ÷ 4 is: 3 with remainder: 1

Sidef

func foo(a,b) {
    return (a+b, a*b);
}

Catching the returned arguments:

var (x, y) = foo(4, 5);
say x;   #=> 9
say y;   #=> 20

Smalltalk

Smalltalk returns a single value from methods, so this task is usually implemented the scheme-way, by passing a lambda-closure which is invoked with the values to return and either operates on the values itself or sets them as the caller's locals (i.e. simular to call-with-values ... values):

foo multipleValuesInto:[:a :b | 
   Transcript show:a; cr.
   Transcript show:b; cr.
]

or:

|val1 val2|
foo multipleValuesInto:[:a :b | 
   val1 := a.
   val2 := b.
].
... do something with val1 and val2...

The called method in foo looks like:

multipleValuesInto: aTwoArgBlock
   ...
   aTwoArgBlock value:<value1> value:<value2>

i.e. it invokes the passed-in lambda closure with the two (return-)values.

Standard ML

Every function returns one value. The conventional way to return multiple values is to return a tuple.

fun addsub (x, y) =
  (x + y, x - y)

You can use pattern matching to extract the components:

let
  val (sum, difference) = addsub (33, 12)
in
  print ("33 + 12 = " ^ Int.toString sum ^ "\n");
  print ("33 - 12 = " ^ Int.toString difference ^ "\n")
end

Swift

Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.

func addsub(x: Int, y: Int) -> (Int, Int) {
  return (x + y, x - y)
}

You can use pattern matching to extract the components:

let (sum, difference) = addsub(33, 12)
println("33 + 12 = \(sum)")
println("33 - 12 = \(difference)")

Tcl

Tcl commands all return a single value, but this value can be a compound value such as a list or dictionary. The result value of a procedure is either the value given to the return command or the result of the final command in the body in the procedure. (Commands that return “no” value actually return the empty string.)

proc addsub {x y} {
    list [expr {$x+$y}] [expr {$x-$y}]
}

This can be then assigned to a single variable with set or to multiple variables with lassign.

lassign [addsub 33 12] sum difference
puts "33 + 12 = $sum, 33 - 12 = $difference"

TXR

TXR functions return material by binding unbound variables.

The following function potentially returns three values, which will happen if called with three arguments, each of which is an unbound variable:

@(define func (x y z))
@  (bind w "discarded")
@  (bind (x y z) ("a" "b" "c"))
@(end)

The binding w, if created, is discarded because w is not in the list of formal parameters. However, w can cause the function to fail because there can already exist a variable w with a value which doesn't match "discarded".

Call:

@(func t r s)

If t, r and s are unbound variables, they get bound to "a", "b" and "c", respectively via a renaming mechanism. This may look like C++ reference parameters or Pascal "var" parameters, and can be used that way, but isn't really the same at all.

Failed call ("1" doesn't match "a"):

@(func "1" r s)

Successful call binding only one new variable:

@(func "a" "b" s)

UNIX Shell

Shell scripts don't directly support returning values from a function, it can be simulated through some clunky code.

#!/bin/sh
funct1() {
  a=$1
  b=`expr $a + 1`
  echo $a $b
}

values=`funct1 5`

set $values
x=$1
y=$2
echo "x=$x"
echo "y=$y"
Output:
x=5
y=6

Ursa

The most straightforward way to return multiple values from a function in Ursa is to return a stream.

This example gets a specified amount of strings from the user, then returns a stream containing them.

def getstrs (int n)
        decl string<> input

        while (> n 0)
                out ": " console
                append (in string console) input
                dec n
        end while

        return input
end getstrs

decl int amount
out "how many strings do you want to enter? " console
set amount (in int console)

decl string<> ret
set ret (getstrs amount)

out endl ret endl console
Output:
how many strings do you want to enter? 5
: these   
: are
: some
: test
: strings

class java.lang.String<these, are, some, test, strings>

VBA

Firt way : User Defined Type

Type Contact
    Name As String
    firstname As String
    Age As Byte
End Type

Function SetContact(N As String, Fn As String, A As Byte) As Contact
    SetContact.Name = N
    SetContact.firstname = Fn
    SetContact.Age = A
End Function

'For use :
Sub Test_SetContact()
Dim Cont As Contact

    Cont = SetContact("SMITH", "John", 23)
    Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old."
End Sub
Output:
SMITH John, 23 years old.

Second way : ByRef argument : (Note : the ByRef Arg could be an array)

Function Divide(Dividend As Integer, Divisor As Integer, ByRef Result As Double) As Boolean
    Divide = True
    On Error Resume Next
    Result = Dividend / Divisor
    If Err <> 0 Then
        Divide = False
        On Error GoTo 0
    End If
End Function

'For use :
Sub test_Divide()
Dim R As Double, Ddd As Integer, Dvs As Integer, B As Boolean

    Ddd = 10: Dvs = 3
    B = Divide(Ddd, Dvs, R)
    Debug.Print "Divide return : " & B & " Result = " & R
    Ddd = 10: Dvs = 0
    B = Divide(Ddd, Dvs, R)
    Debug.Print "Divide return : " & B & " Result = " & R
End Sub
Output:
Divide return : True Result = 3,33333333333333
Divide return : False Result = 1,#INF

Third way : ParramArray

Function Multiple_Divide(Dividend As Integer, Divisor As Integer, ParamArray numbers() As Variant) As Long
Dim i As Integer

    On Error GoTo ErrorHandler
    numbers(LBound(numbers)) = Dividend / Divisor
    For i = LBound(numbers) + 1 To UBound(numbers)
        numbers(i) = numbers(i - 1) / Divisor
    Next i
    Multiple_Divide = 1: Exit Function
ErrorHandler:
    Multiple_Divide = 0
End Function

'For use :
Sub test_Multiple_Divide()
Dim Arr(3) As Variant, Ddd As Integer, Dvs As Integer, L As Long, i As Integer

    Ddd = 10: Dvs = 3
    L = Multiple_Divide(Ddd, Dvs, Arr(0), Arr(1), Arr(2), Arr(3))
    Debug.Print "The function return : " & L
    Debug.Print "The values in return are : "
    For i = LBound(Arr) To UBound(Arr)
        Debug.Print Arr(i)
    Next i
    Erase Arr
    Debug.Print "--------------------------------------"
    Ddd = 10: Dvs = 0
    L = Multiple_Divide(Ddd, Dvs, Arr(0), Arr(1), Arr(2), Arr(3))
    Debug.Print "The function return : " & L
    Debug.Print "The values in return are : "
    For i = LBound(Arr) To UBound(Arr)
        Debug.Print IIf(Arr(i) = "", "vbNullString", "Null")
    Next i
End Sub
Output:
The function return : 1
The values in return are : 
 3,33333333333333 
 1,11111111111111 
 0,37037037037037 
 0,123456790123457 
--------------------------------------
The function return : 0
The values in return are : 
vbNullString
vbNullString
vbNullString
vbNullString

Fourth way : the variant() function

Function List() As String()
Dim i&, Temp(9) As String

    For i = 0 To 9
        Temp(i) = "Liste " & i + 1
    Next
    List = Temp
End Function

'For use :
Sub test_List()
Dim myArr() As String, i As Integer
'Note : you don't need to Dim your array !
    myArr = List()
    For i = LBound(myArr) To UBound(myArr)
        Debug.Print myArr(i)
    Next
End Sub
Output:
Liste 1
Liste 2
Liste 3
Liste 4
Liste 5
Liste 6
Liste 7
Liste 8
Liste 9
Liste 10

Visual FoxPro

*!* Return multiple values from a function
*!* The simplest way is to pass the parameters by reference
*!* either by SET UDFPARMS TO REFERENCE, or prefix the variables with @.
LOCAL a, b
a = 5
b = 6
? "Sum =", AddUp(@a, @b)    && Displays 11
? "a =", a, "b =", b        && Displays 4, 5
? "Sum =", AddUp(@a, @b)    && Displays 9

FUNCTION AddUp(n1, n2)
LOCAL n 
n = n1 + n2
n1 = n1 - 1
n2 = n2 - 1 
RETURN n
ENDFUNC

Wren

In Wren, one would return multiple values from a function or method by using some sort of Sequence object, usually a List though a Map could be used if you needed named returns.

var splitName = Fn.new { |fullName| fullName.split(" ") }

var names = splitName.call("George Bernard Shaw")
System.print("First name: %(names[0]), middle name: %(names[1]) and surname: %(names[2]).")
Output:
First name: George, middle name: Bernard and surname: Shaw.

XPL0

include c:\cxpl\codes;          \intrinsic 'code' declarations

proc Rect2Polar(X,Y,A,D);       \Return two polar coordinate values
real X,Y,A,D;
[A(0):= ATan2(Y,X);
 D(0):= Sqrt(X*X+Y*Y);
]; \Rect2Polar

real Ang, Dist;
[Rect2Polar(4.0, 3.0, @Ang, @Dist);  \("@" is a new feature similar to 'addr')
RlOut(0, Ang); 
RlOut(0, Dist); 
CrLf(0);
]
Output:

(angle is in radians)

    0.64350    5.00000

Z80 Assembly

A function can return multiple values by altering the contents of multiple registers. Code is CALLed as a subroutine.

In this trivial example, the function returns 0xABCD and 0xFFFF.

foo:
    ld hl,&ABCD
    ld bc,&FFFF
    ret

zkl

fcn f{return(1,2,"three")}
a,b,c:=f()  // a==1, b==2, c=="three"