Return multiple values: Difference between revisions

add BLC solution
m (Updated description and link for Fōrmulæ solution)
imported>Tromp
(add BLC solution)
 
(47 intermediate revisions by 25 users not shown)
Line 10:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F addsub(x, y)
R (x + y, x - y)
 
V (summ, difference) = addsub(33, 12)
print(‘33 + 12 = ’summ)
print(‘33 - 12 = ’difference)</langsyntaxhighlight>
 
{{out}}
Line 22:
33 - 12 = 21
</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}}==
<langsyntaxhighlight Lisplang="lisp">;; To return multiple values:
(defun multiple-values (a b)
(mv a b))
Line 31 ⟶ 78:
(mv-let (x y)
(multiple-values 1 2)
(+ x y))</langsyntaxhighlight>
<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}}==
Line 40 ⟶ 184:
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.
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
procedure MultiReturn is
Line 55 ⟶ 199:
Put_Line ("Diff:" & Integer'Image (thediff));
end MultiReturn;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 66 ⟶ 210:
<br>
Tested with Agena 2.9.5 Win32
<langsyntaxhighlight lang="agena"># define a function returning three values
mv := proc() is
return 1, 2, "three"
Line 74 ⟶ 218:
local a, b, c := mv();
print( c, b, a )
epocs</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 80 ⟶ 224:
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.
<langsyntaxhighlight lang="algol68"># example mode for returning multiple values from a procedure #
MODE PAIR = STRUCT( STRING name, INT value );
 
Line 98 ⟶ 242:
# access the components separately #
print( ( name OF get pair( 1 ), value OF get pair( 2 ), newline ) )
)</langsyntaxhighlight>
{{out}}
<pre>
Line 107 ⟶ 251:
=={{header|ALGOL W}}==
Algol W procedures can't return arrays but records can be used to return multiple values.
<langsyntaxhighlight lang="algolw">begin
% example using a record type to return multiple values from a procedure %
record Element ( string(2) symbol; integer atomicNumber );
Line 134 ⟶ 278:
end
 
end.</langsyntaxhighlight>
 
=={{header|ANSIAmazing Standard BASICHopper}}==
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}}==
<langsyntaxhighlight lang="rebol">addsub: function [x y]->
@[x+y x-y]
 
Line 160 ⟶ 349:
 
print [a "+" b "=" result\0]
print [a "-" b "=" result\1]</langsyntaxhighlight>
 
{{out}}
Line 169 ⟶ 358:
=={{header|ATS}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<syntaxhighlight lang="ats">//
<lang ATS>//
#include
"share/atspre_staload.hats"
Line 188 ⟶ 377:
println! ("33 + 12 = ", sum);
println! ("33 - 12 = ", diff);
end (* end of [main0] *)</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
Functions may return one value. The conventional way to return multiple values is to bundle them into an Array.
<langsyntaxhighlight AutoHotkeylang="autohotkey">addsub(x, y) {
return [x + y, x - y]
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
Return an array.
<syntaxhighlight lang="autoit">
<lang AutoIt>
Func _AddSub($iX, $iY)
Local $aReturn[2]
Line 206 ⟶ 395:
Return $aReturn
EndFunc
</syntaxhighlight>
</lang>
 
=={{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}}===
BaCon can return homogeneous dynamic arrays, or RECORD data holding heterogeneous types.
 
<langsyntaxhighlight lang="freebasic">' Return multiple values
RECORD multi
LOCAL num
Line 230 ⟶ 439:
PRINT rec.num
PRINT rec.s$[0]
PRINT rec.s$[1]</langsyntaxhighlight>
 
{{out}}
Line 240 ⟶ 449:
==={{header|BBC BASIC}}===
The most straightforward way of returning multiple values is to specify them as RETURNed parameters.
<langsyntaxhighlight lang="bbcbasic"> PROCsumdiff(5, 3, sum, diff)
PRINT "Sum is " ; sum
PRINT "Difference is " ; diff
Line 248 ⟶ 457:
c = a + b
d = a - b
ENDPROC</langsyntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 NUMERIC SUM,DIFF
110 CALL SUMDIFF(5,3,SUM,DIFF)
120 PRINT "Sum is";SUM:PRINT "Difference is";DIFF
Line 257 ⟶ 466:
140 DEF SUMDIFF(A,B,REF C,REF D)
150 LET C=A+B:LET D=A-B
160 END DEF</langsyntaxhighlight>
==={{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}}==
{{trans|Haskell}}
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<langsyntaxhighlight lang="bracmat">(addsub=x y.!arg:(?x.?y)&(!x+!y.!x+-1*!y));</langsyntaxhighlight>
You can use pattern matching to extract the components:
<langsyntaxhighlight lang="bracmat">( addsub$(33.12):(?sum.?difference)
& out$("33 + 12 = " !sum)
& out$("33 - 12 = " !difference)
);</langsyntaxhighlight>
{{out}}
<pre>33 + 12 = 45
Line 274 ⟶ 523:
=={{header|C}}==
C has structures which can hold multiple data elements of varying types.
<langsyntaxhighlight lang="c">#include<stdio.h>
 
typedef struct{
Line 298 ⟶ 547:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 305 ⟶ 554:
 
C99 and above also allow structure literals to refer to the name, rather than position, of the element to be initialized:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef struct {
Line 322 ⟶ 571:
printf("The name's %s. %s %s.\n", me.last, me.first, me.last);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>The name's Bond. James Bond.
Line 328 ⟶ 577:
 
=={{header|C sharp|C#}}==
The preferred way to return multiple values in C# is to use "out" paremetersparameters on the method. This can be in addition to the value returned by the method.
<langsyntaxhighlight lang="c sharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 350 ⟶ 599:
min = sortedNums.First();
}
}</langsyntaxhighlight>
{{out}}
<pre>Min: -3
Line 357 ⟶ 606:
=={{header|C++}}==
Since C++11, the C++-standard-library includes tuples, as well as an easy way to destructure them.
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <array>
#include <cstdint>
Line 375 ⟶ 624:
std::tie(min, max) = minmax(numbers.data(), numbers.size());
std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}</langsyntaxhighlight>
{{out}}
<PRE>The smallest number is -10, the biggest 987!</PRE>
Line 382 ⟶ 631:
Every function returns one value.
The conventional way to return multiple values is to bundle them into an array.
<langsyntaxhighlight Clipperlang="clipper">Function Addsub( x, y )
Return { x+y, x-y }</langsyntaxhighlight>
 
=={{header|Clojure}}==
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].
<langsyntaxhighlight lang="clojure">(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))</langsyntaxhighlight>
In complex cases, it would make more sense to return a map, which can be destructed in a similar manner.
<langsyntaxhighlight lang="clojure">(defn quot-rem [m n]
{:q (quot m n)
:r (rem m n)})
Line 402 ⟶ 651:
(let [{:keys [q r]} (quot-rem 11 3)]
(println q)
(println r))</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="cmake"># Returns the first and last characters of string.
function(firstlast string first last)
# f = first character.
Line 421 ⟶ 704:
 
firstlast("Rosetta Code" begin end)
message(STATUS "begins with ${begin}, ends with ${end}")</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 436 ⟶ 719:
{{works with|GnuCOBOL}}
 
<syntaxhighlight lang="cobol">
<lang COBOL>
identification division.
program-id. multiple-values.
Line 510 ⟶ 793:
goback.
end function multiples.
</syntaxhighlight>
</lang>
 
{{out}}
Line 524 ⟶ 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.
<langsyntaxhighlight lang="lisp">(defun return-three ()
3)</langsyntaxhighlight>
The next possibility is that of returning no values at all. For this, the <code>values</code> function is used, with no arguments:
<langsyntaxhighlight lang="lisp">(defun return-nothing ()
(values))</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="lisp">[1]> (defun add-sub (x y) (values-list (list (+ x y) (- x y))))
ADD-SUB
[2]> (add-sub 4 2) ; 6 (primary) and 2
Line 541 ⟶ 824:
10
[5]> (multiple-value-call #'+ (add-sub 4 2) (add-sub 3 1)) ; 6+2+4+2
14</langsyntaxhighlight>
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>:
<langsyntaxhighlight lang="lisp">(car (values)) ;; no error: same as (car nil)</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="lisp">(values (values 1 2 3) (values) 'a)</langsyntaxhighlight>
yields three values:
<pre>-> 1; NIL; A</pre>
This also means that <code>values</code> can be used to reduce a multiple value to a single value:
<langsyntaxhighlight lang="lisp">;; return exactly one value, no matter how many expr returns,
;; nil if expr returns no values
(values expr)</langsyntaxhighlight>
Multiple values are extracted in several ways.
 
1. Binding to variables:
<langsyntaxhighlight lang="lisp">(multiple-value-bind (dividend remainder) (truncate 16 3)
;; in this scope dividend is 5; remainder is 1
)</langsyntaxhighlight>
 
2. Conversion to a list:
<langsyntaxhighlight lang="lisp">(multiple-value-list (truncate 16 3)) ;; yields (5 1)</langsyntaxhighlight>
 
3. Reification of multiple values as arguments to another function:
<langsyntaxhighlight lang="lisp">;; pass arguments 5 1 to +, resulting in 6:
(multiple-value-call #'+ (truncate 16 3))</langsyntaxhighlight>
 
4. Assignment to variables:
<langsyntaxhighlight lang="lisp">;; assign 5 to dividend, 1 to remainder:
(multiple-value-setq (dividend remainder) (truncate 16 1))</langsyntaxhighlight>
<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:
<langsyntaxhighlight lang="lisp">(setf (values dividend remainder) (truncate 16 1))</langsyntaxhighlight>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
# In Cowgol, subroutines can simply define multiple output parameters.
Line 599 ⟶ 882:
 
print("Min: "); print_i8(least); print_nl();
print("Max: "); print_i8(most); print_nl();</langsyntaxhighlight>
 
{{out}}
Line 607 ⟶ 890:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.typecons, std.algorithm;
 
 
Line 634 ⟶ 917:
 
writefln("33 + 12 = %d\n33 - 12 = %d", a, b);
}</langsyntaxhighlight>
{{out}}
<pre>33 + 12 = 45
Line 641 ⟶ 924:
=={{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>.
<langsyntaxhighlight lang="dc">[ S1 S2 l2 l1 / L2 L1 % ] s~
1337 42 l~ x f</langsyntaxhighlight>
{{out}}
<pre>35
Line 649 ⟶ 932:
=={{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.
<langsyntaxhighlight Delphilang="delphi">program ReturnMultipleValues;
 
{$APPTYPE CONSOLE}
Line 665 ⟶ 948:
Writeln(x);
Writeln(y);
end.</langsyntaxhighlight>
 
=={{header|Dyalect}}==
Line 671 ⟶ 954:
A typical way to return multiple values in Dyalect is to use tuples:
 
<langsyntaxhighlight Dyalectlang="dyalect">func divRem(x, y) {
(x / y, x % y)
}</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">function-returning-multiple-values:
10 20
 
!print !print function-returning-multiple-values
</syntaxhighlight>
</lang>
{{out}}
<pre>10
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}}==
One can return the result of the '''values''' function, or a list.
<langsyntaxhighlight lang="scheme">
(define (plus-minus x y)
(values (+ x y) (- x y)))
Line 698 ⟶ 997:
(plus-minus 3 4)
→ (7 -1)
</syntaxhighlight>
</lang>
 
=={{header|ECL}}==
<syntaxhighlight lang="text">MyFunc(INTEGER i1,INTEGER i2) := FUNCTION
RetMod := MODULE
EXPORT INTEGER Add := i1 + i2;
Line 712 ⟶ 1,011:
MyFunc(3,4).Add;
MyFunc(3,4).Prod;
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
Every function returns one value. Multiple values can be returned in a tuple.
<langsyntaxhighlight Eiffellang="eiffel">some_feature: TUPLE
do
Result := [1, 'j', "r"]
end</langsyntaxhighlight>
Greater control over the type of return values can also be enforced by explicitly declaring the type of the generic parameters.
<langsyntaxhighlight Eiffellang="eiffel">some_feature: TUPLE[INTEGER_32, CHARACTER_8, STRING_8]
do
--Result := [ ] -- compile error
Line 727 ⟶ 1,026:
Result := [1, 'j', "r"] -- okay
Result := [1, 'j', "r", 1.23] -- also okay
end</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 752 ⟶ 1,051:
console.printLine("Min: ",min," Max: ",max)
}</langsyntaxhighlight>
=== 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}}
<pre>
Line 760 ⟶ 1,081:
=={{header|Elixir}}==
Elixir returns in the tuple form when returning more than one value.
<langsyntaxhighlight lang="elixir">defmodule RC do
def addsub(a, b) do
{a+b, a-b}
Line 767 ⟶ 1,088:
 
{add, sub} = RC.addsub(7, 4)
IO.puts "Add: #{add},\tSub: #{sub}"</langsyntaxhighlight>
 
{{out}}
Line 775 ⟶ 1,096:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Put this code in return_multi.erl and run it as "escript return_multi.erl"
 
-module(return_multi).
Line 785 ⟶ 1,106:
multiply(A, B) ->
{A * B, A + B, A - B}.
</syntaxhighlight>
</lang>
{{out}}
<pre>12 7 -1
Line 792 ⟶ 1,113:
=={{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.
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM RETURN_VALUES
 
Line 805 ⟶ 1,126:
PRINT("Difference is";DIFF)
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}}==
Any Euphoria object can be returned. A sequence of objects can be returned, made from multiple data types as in this example.
<langsyntaxhighlight lang="euphoria">include std\console.e --only for any_key, to help make running this program easy on windows GUI
 
integer aWholeNumber = 1
Line 822 ⟶ 1,161:
result = addmultret(aWholeNumber, aFloat, aSequence) --call function, assign what it gets into result - {9.999999, 23.999988}
? result
any_key()</langsyntaxhighlight>
 
{{out}}
Line 831 ⟶ 1,170:
A function always returns exactly one value.
To return multiple results, they are typically packed into a tuple:
<langsyntaxhighlight lang="fsharp">let addSub x y = x + y, x - y
 
let sum, diff = addSub 33 12
printfn "33 + 12 = %d" sum
printfn "33 - 12 = %d" diff</langsyntaxhighlight>
 
Output parameters from .NET APIs are automatically converted to tuples by the compiler.
Line 843 ⟶ 1,182:
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.
<langsyntaxhighlight lang="factor">USING: io kernel math prettyprint ;
IN: script
 
Line 852 ⟶ 1,191:
 
[ "15 * 3 = " write . ]
[ "15 / 3 = " write . ] bi*</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="false">[\$@$@*@@/]f: { in: a b, out: a*b a/b }
6 2f;! .`' ,. { 3 12 }</langsyntaxhighlight>
 
=={{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.).
<langsyntaxhighlight lang="forth">: muldiv ( a b -- a*b a/b )
2dup / >r * r> ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{trans|Haskell}}
<langsyntaxhighlight Fortranlang="fortran">module multiple_values
implicit none
type res
Line 886 ⟶ 1,225:
print *, addsub(33, 22)
end program
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' One way to return multiple values is to use ByRef parameters for the additional one(s)
Line 941 ⟶ 1,280:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 954 ⟶ 1,293:
=={{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.
<langsyntaxhighlight lang="frink">
divMod[a, b] := [a div b, a mod b]
 
[num, remainder] = divMod[10, 3]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
{{trans|Scala}}
<langsyntaxhighlight lang="funl">def addsub( x, y ) = (x + y, x - y)
 
val (sum, difference) = addsub( 33, 12 )
 
println( sum, difference, addsub(33, 12) )</langsyntaxhighlight>
 
{{out}}
Line 978 ⟶ 1,317:
 
Here is an example of returning multiple values using pointers:
<langsyntaxhighlight lang="futurebasic">
include "ConsoleWindow"
 
local fn ReturnMultipleValues( strIn as Str255, strOut as ^Str255, letterCount as ^long )
dim as 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
 
dim as Str255 outStr
dim as long outCount
 
fn ReturnMultipleValues( "Hello, World!", @outStr, @outCount )
print outStr; ". The combined strings have "; outCount; " letters in them."
 
</lang>
HandleEvents
</syntaxhighlight>
 
Output:
Line 1,009 ⟶ 1,348:
 
Another way to pass multiple values from a function is with records (AKA structures):
<syntaxhighlight lang="text">
include "ConsoleWindow"
 
// Elements in global array
_maxDim = 3
 
begin record Addresses
dim as Str63 name
dim as Str15 phone
dim as long zip
end record
 
begin globals
dim as 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
 
Line 1,042 ⟶ 1,379:
fn FillRecord( gAddressData(0) )
 
dim as short i
 
for i = 0 to 2
print gAddressData.name(i); ", ";
print gAddressData.phone(i); ", Zip:";
print gAddressData.zip(i)
next
 
</lang>
HandleEvents
</syntaxhighlight>
 
Output:
Line 1,059 ⟶ 1,397:
 
You can also use global arrays to return multiple values from a function as in this example:
<syntaxhighlight lang="text">
include "ConsoleWindow"
 
// Elements in global array
_maxDim = 3
 
begin globals
dim as Str31 gAddressArray(_maxDim, _maxDim)
end globals
 
Line 1,072 ⟶ 1,408:
array( 0, 0 ) = "John Doe"
array( 1, 0 ) = "Mary Jones"
array( 2, 0 ) = "Bill Smith"
 
array( 0, 1 ) = "555-359-4411"
Line 1,086 ⟶ 1,422:
fn FillRecord( gAddressArray( 0, 0 ) )
 
dim as 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
 
</lang>
HandleEvents
</syntaxhighlight>
 
Output:
Line 1,104 ⟶ 1,442:
 
Here is another example using FB's containers -- bit buckets that can hold up to 2GB of data contingent on system memory.
<syntaxhighlight lang="text">
include "ConsoleWindow"
 
begin globals
// An FB container can hold up to 2GB of data, contingent on system memory
dim as container gC1, gC2
end globals
 
Line 1,151 ⟶ 1,487:
// Check the new results
print gC1 : print gC2
 
</lang>
HandleEvents
</syntaxhighlight>
 
Output:
Line 1,176 ⟶ 1,514:
=={{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}}==
Functions can return multiple values in Go:
<langsyntaxhighlight lang="go">func addsub(x, y int) (int, int) {
return x + y, x - y
}</langsyntaxhighlight>
Or equivalently using named return style:
<langsyntaxhighlight lang="go">func addsub(x, y int) (sum, difference int) {
sum = x + y
difference = x - y
return
}</langsyntaxhighlight>
When a function returns multiple values, you must assign to a comma-separated list of targets:
<langsyntaxhighlight lang="go">sum, difference := addsub(33, 12)
fmt.Printf("33 + 12 = %d\n", sum)
fmt.Printf("33 - 12 = %d\n", difference)</langsyntaxhighlight>
::<langsyntaxhighlight lang="go">package main
 
import (
Line 1,260 ⟶ 1,606:
puss, poo := myCat.Puss()
fmt.Println(puss, poo) // prt Kitty Cat
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
In Groovy functions return one value. One way to return multiple ones is to use anonymous maps as a sort of tuple.
<langsyntaxhighlight lang="groovy">def addSub(x,y) {
[
sum: x+y,
difference: x-y
]
}</langsyntaxhighlight>
Result:
<langsyntaxhighlight lang="groovy">addSub(10,12)
["sum":22, "difference":-2]</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="groovy">def addSub2(x,y) {
[ x+y , x-y ]
}
Line 1,283 ⟶ 1,629:
def (sum, diff) = addSub2(50, 5)
assert sum == 55
assert diff == 45</langsyntaxhighlight>
 
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 ⟶ 1,635:
=={{header|Harbour}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into an array.
<langsyntaxhighlight lang="visualfoxpro">FUNCTION Addsub( x, y )
RETURN { x + y, x - y }</langsyntaxhighlight>
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}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<langsyntaxhighlight lang="haskell"> addsub x y = (x + y, x - y)</langsyntaxhighlight>
You can use pattern matching to extract the components:
<langsyntaxhighlight lang="haskell">main = do
let (sum, difference) = addsub 33 12
putStrLn ("33 + 12 = " ++ show sum)
putStrLn ("33 - 12 = " ++ show difference)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,305 ⟶ 1,671:
 
The following examples return 1, 2, 3 in different ways:
<langsyntaxhighlight Iconlang="icon">procedure retList() # returns as ordered list
return [1,2,3]
end
Line 1,330 ⟶ 1,696:
procedure retRecord() # return as a record, least general method
return retdata(1,2,3)
end</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="j"> 1 2+3 4
4 6</langsyntaxhighlight>
 
=={{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}}
<langsyntaxhighlight Javalang="java">import java.util.List;
import java.util.ArrayList;
import java.util.Map;
Line 1,438 ⟶ 1,839:
}
}
}</langsyntaxhighlight>
'''Otherwise'''
<langsyntaxhighlight Javalang="java">public class Values {
private final Object[] objects;
public Values(Object ... objects) {
Line 1,470 ⟶ 1,871:
System.out.println();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,480 ⟶ 1,881:
=={{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.
<langsyntaxhighlight JavaScriptlang="javascript">//returns array with three values
var arrBind = function () {
return [1, 2, 3]; //return array of three items to assign
Line 1,503 ⟶ 1,904:
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"}</langsyntaxhighlight>
 
=={{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: <langsyntaxhighlight lang="jq"># 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 ];
</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:<langsyntaxhighlight lang="jq">
1
2</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function addsub(x, y)
return x + y, x - y
end</langsyntaxhighlight>
<pre>julia> addsub(10,4)
(14,6)</pre>
Line 1,525 ⟶ 1,926:
=={{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.
<langsyntaxhighlight lang="scala">// version 1.0.6
 
/* implicitly returns a Pair<Int, Int>*/
Line 1,535 ⟶ 1,936:
println("The smallest number is $min")
println("The largest number is $max")
}</langsyntaxhighlight>
 
{{out}}
Line 1,545 ⟶ 1,946:
=={{header|Lambdatalk}}==
Lambdatalk can retun several values glued into conses or arrays.
<langsyntaxhighlight lang="scheme">
{def foo
{lambda {:n}
Line 1,561 ⟶ 1,962:
{bar 10}
-> [9,10,11]
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define multi_value() => {
return (:'hello word',date)
}
Line 1,572 ⟶ 1,973:
 
'x: '+#x
'\ry: '+#y</langsyntaxhighlight>
{{out}}
<pre>x: hello word
Line 1,580 ⟶ 1,981:
=={{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.
<langsyntaxhighlight lang="lb">data$ ="5 6 7 22 9 3 4 8 7 6 3 -5 2 1 8 9"
 
a$ =minMax$( data$)
Line 1,600 ⟶ 2,001:
loop until 0
minMax$ =str$( min) +" " +str$( max)
end function</langsyntaxhighlight>
<pre>
Minimum was -5 & maximum was 22
Line 1,608 ⟶ 2,009:
No support for returning multiple values, but (similar to Scala), a Tuple can be returned.
 
<langsyntaxhighlight Lilylang="lily">define combine(a: Integer, b: String): Tuple[Integer, String]
{
return <[a, b]>
}</langsyntaxhighlight>
 
The current version (0.17) has no support for destructuring Tuple assigns.
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function addsub( a, b )
return a+b, a-b
end
 
s, d = addsub( 7, 5 )
print( s, d )</langsyntaxhighlight>
 
 
 
=={{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}}==
<langsyntaxhighlight Maplelang="maple">> sumprod := ( a, b ) -> (a + b, a * b):
> sumprod( x, y );
x + y, x y
 
> sumprod( 2, 3 );
5, 6</langsyntaxhighlight>
The parentheses are needed here only because of the use of arrow ("->") notation to define the procedure. One could do, instead:
<langsyntaxhighlight Maplelang="maple">sumprod := proc( a, b ) a + b, a * b end:</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">addsub [x_,y_]:= List [x+y,x-y]
addsub[4,2]</langsyntaxhighlight>
{{out}}
<pre>{6,2}</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> function [a,b,c]=foo(d)
a = 1-d;
b = 2+d;
c = a+b;
end;
[x,y,z] = foo(5) </langsyntaxhighlight>
{{out}}
<langsyntaxhighlight Matlablang="matlab"> > [x,y,z] = foo(5)
x = -4
y = 7
z = 3 </langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">f(a, b) := [a * b, a + b]$
 
[u, v]: f(5, 6);
[30, 11]</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 1,666 ⟶ 2,229:
 
===addsub.m===
<langsyntaxhighlight lang="mercury">:- module addsub.
 
:- interface.
Line 1,693 ⟶ 2,256:
D = X - Y.
 
:- end_module addsub.</langsyntaxhighlight>
 
===Use and output===
Line 1,705 ⟶ 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>:
 
<langsyntaxhighlight Mercurylang="mercury">:- func addsub(int, int) = {int, int}.
addsub(X, Y) = { X + Y, X - Y }.</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight Mercurylang="mercury"> {S, D} = addsub(X, Y),</langsyntaxhighlight>
 
All other code remains exactly the same as does the use and output of it.
Line 1,720 ⟶ 2,283:
An example of this follows:
 
<langsyntaxhighlight Mercurylang="mercury">:- module addsub.
 
:- interface.
Line 1,747 ⟶ 2,310:
addsub(X, Y) = twin(X + Y, X - Y).
 
:- end_module addsub.</langsyntaxhighlight>
 
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 ⟶ 2,319:
To return multiple values in min, simply leave them on the data stack.
{{works with|min|0.19.6}}
<langsyntaxhighlight lang="min">(over over / '* dip) :muldiv</langsyntaxhighlight>
 
=={{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}}==
To return multiple values in Nemerle, package them into a tuple.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle.Assertions;
Line 1,782 ⟶ 2,352:
WriteLine($"Min of nums = $min; max of nums = $max");
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
Line 1,788 ⟶ 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.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,890 ⟶ 2,460:
setRightVal(sv_)
return
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
Every function returns one value. We can return a tuple instead:
<langsyntaxhighlight lang="nim">proc addsub(x, y: int): (int, int) =
(x + y, x - y)
 
var (a, b) = addsub(12, 15)</langsyntaxhighlight>
 
Or manipulate the parameters directly:
<langsyntaxhighlight lang="nim">proc addsub(x, y: int; a, b: var int) =
a = x + y
b = x - y
 
var a, b: int
addsub(12, 15, a, b)</langsyntaxhighlight>
 
=={{header|Objeck}}==
Easiest way to return multiple values is to use in/out objects. The language also supports returning collections.
<langsyntaxhighlight lang="objeck">class Program {
function : Main(args : String[]) ~ Nil {
a := IntHolder->New(3); b := IntHolder->New(7);
Line 1,919 ⟶ 2,489:
a->Set(a->Get() + 2); b->Set(b->Get() + 13);
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<langsyntaxhighlight lang="ocaml">let addsub x y =
x + y, x - y</langsyntaxhighlight>
(Note that parentheses are not necessary for a tuple literal in OCaml.)
 
You can use pattern matching to extract the components:
<langsyntaxhighlight lang="ocaml">let sum, difference = addsub 33 12 in
Printf.printf "33 + 12 = %d\n" sum;
Printf.printf "33 - 12 = %d\n" difference</langsyntaxhighlight>
 
=={{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 :
<langsyntaxhighlight Oforthlang="oforth">import: date
 
: returnFourValues 12 13 14 15 ;
Line 1,944 ⟶ 2,514:
 
"\nShowing one object containing four values returned on the parameter stack:" println
returnOneObject .s clr</langsyntaxhighlight>
 
Output:
Line 1,960 ⟶ 2,530:
=={{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:
<syntaxhighlight lang="oorexx">
<lang ooRexx>
r = addsub(3, 4)
say r[1] r[2]
Line 1,967 ⟶ 2,537:
use arg x, y
return .array~of(x + y, x - y)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,976 ⟶ 2,546:
Demonstrated with vectors, using OOP and a pseudo-assign trick:
 
<langsyntaxhighlight lang="oxygenbasic">
 
'============
Line 2,021 ⟶ 2,591:
print aa.ShowValues() 'result 100,200,-300,400
 
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
The usual way to return multiple values is to put them in a vector:
<langsyntaxhighlight lang="parigp">foo(x)={
[x^2, x^3]
};</langsyntaxhighlight>
 
=={{header|Perl}}==
Functions may return lists of values:
<langsyntaxhighlight lang="perl">sub foo {
my ($a, $b) = @_;
return $a + $b, $a * $b;
}</langsyntaxhighlight>
 
=={{header|Phix}}==
{{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.
<!--<langsyntaxhighlight Phixlang="phix">-->
<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;">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>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into an array.
<langsyntaxhighlight lang="php">function addsub($x, $y) {
return array($x + $y, $x - $y);
}</langsyntaxhighlight>
You can use the <code>list()</code> construct to assign to multiple variables:
<langsyntaxhighlight lang="php">list($sum, $difference) = addsub(33, 12);
echo "33 + 12 = $sum\n";
echo "33 - 12 = $difference\n";</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="php">function multiples($param1, &$param2) {
if ($param1 == 'bob') {
$param2 = 'is your grandmother';
Line 2,072 ⟶ 2,642:
 
echo 'Second run: ' . multiples('bob', $y) . "\r\n";
echo "Param 2 from second run: '${y}'\r\n";</langsyntaxhighlight>
 
The above will yield the following output:
Line 2,079 ⟶ 2,649:
Second run: 1
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}}==
A PicoLisp function returns a single value. For multiple return values, a cons pair or a list may be used.
<langsyntaxhighlight PicoLisplang="picolisp">(de addsub (X Y)
(list (+ X Y) (- X Y)) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (addsub 4 2)
-> (6 2)
: (addsub 3 1)
Line 2,092 ⟶ 2,701:
-> 10
: (sum + (addsub 4 2) (addsub 3 1))
-> 14</langsyntaxhighlight>
 
=={{header|Pike}}==
Multiple values are returned through an array.
An array can be assigned to separate variables.
<langsyntaxhighlight Pikelang="pike">array(int) addsub(int x, int y)
{
return ({ x+y, x-y });
}
 
[int z, int w] = addsub(5,4);</langsyntaxhighlight>
 
=={{header|PL/I}}==
Example 1 illustrates a function that returns an array:
<langsyntaxhighlight PLlang="pl/Ii"> define structure 1 h,
2 a (10) float;
declare i fixed binary;
Line 2,117 ⟶ 2,726:
end;
return (p);
end sub;</langsyntaxhighlight>
Example 2 illustrates a function that returns a general data structure:
<langsyntaxhighlight PLlang="pl/Ii"> define structure 1 customer,
2 name,
3 surname character (20),
Line 2,133 ⟶ 2,742:
get edit (c.street, c.suburb, c.zip) (L);
return (c);
end sub2;</langsyntaxhighlight>
Example 3 illustrates the return of two values as a complex value:
<langsyntaxhighlight PLlang="pl/Ii">comp: procedure(a, b) returns (complex);
declare (a, b) float;
 
return (complex(a, b) );
end comp;</langsyntaxhighlight>
 
=={{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 otherA number intocalled thefirst product.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>
123 Hello World! yes
The product is 45
The quotient is 5
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function multiple-value ($a, $b) {
[pscustomobject]@{
Line 2,175 ⟶ 2,810:
$m.a
$m.b
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,186 ⟶ 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).
<langsyntaxhighlight 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.
Procedure example_1(x, y, Array r(1)) ;array r() will contain the return values
Line 2,218 ⟶ 2,853:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.
<langsyntaxhighlight lang="python">def addsub(x, y):
return x + y, x - y</langsyntaxhighlight>
(Note that parentheses are not necessary for a tuple literal in Python.)
 
You can assign to a comma-separated list of targets:
<langsyntaxhighlight lang="python">sum, difference = addsub(33, 12)
print "33 + 12 = %s" % sum
print "33 - 12 = %s" % difference</langsyntaxhighlight>
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 ⟶ 2,888:
=={{header|R}}==
The conventional way to return multiple values is to bundle them into a list.
<langsyntaxhighlight Rlang="r">addsub <- function(x, y) list(add=(x + y), sub=(x - y))</langsyntaxhighlight>
 
=={{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"
<langsyntaxhighlight Racketlang="racket">#lang racket
(values 4 5)
 
Line 2,263 ⟶ 2,898:
(call/cc
(lambda (return)
(apply return return-list))))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,270 ⟶ 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:
 
<syntaxhighlight lang="raku" perl6line>sub addmul($a, $b) {
$a + $b, $a * $b
}
 
my ($add, $mul) = addmul 3, 7;</langsyntaxhighlight>
 
In this example, the variable <tt>$add</tt> now holds the number 10, and <tt>$mul</tt> the number 21.
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">define multiReturn use $v
$v each
 
3 multiReturn</langsyntaxhighlight>
{{out}}
<pre>2
1
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}}==
Functions take and return values via a stack. This makes returning multiple values easy.
<langsyntaxhighlight Retrolang="retro">: addSubtract ( xy-nm )
2over - [ + ] dip ;</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,300 ⟶ 2,945:
<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.
<langsyntaxhighlight REXXlang="rexx">/*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.*/
Line 2,320 ⟶ 2,965:
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,337 ⟶ 2,982:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Func AddSub 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}}==
Line 2,346 ⟶ 3,004:
 
Use an array literal:
<langsyntaxhighlight lang="ruby">def addsub(x, y)
[x + y, x - y]
end</langsyntaxhighlight>
Or use <code>return</code> with 2 or more values:
<langsyntaxhighlight lang="ruby">def addsub(x, y)
return x + y, x - y
end</langsyntaxhighlight>
 
(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.
<langsyntaxhighlight lang="ruby">sum, difference = addsub(33, 12)
puts "33 + 12 = #{sum}"
puts "33 - 12 = #{difference}"</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
Courtesy http://dkokenge.com/rbp
<br>Gets the UTC time from the web
<langsyntaxhighlight lang="runbasic">a$ = timeInfo$()
print " UTC:";word$(a$,1,"|")
print "Date:";word$(a$,2,"|")
Line 2,374 ⟶ 3,032:
t$ = time$()
timeInfo$ = utc$;"|";d$;"|";t$
end function</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 2,380 ⟶ 3,038:
Rust supports ADT, thus function can return tuple.
 
<langsyntaxhighlight lang="rust">fn multi_hello() -> (&'static str, i32) {
("Hello",42)
}
Line 2,388 ⟶ 3,046:
println!("{},{}",str,num);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,397 ⟶ 3,055:
=={{header|Scala}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<langsyntaxhighlight lang="scala">def addSubMult(x: Int, y: Int) = (x + y, x - y, x * y)</langsyntaxhighlight>
A more detailed declaration would be:
<langsyntaxhighlight lang="scala">
def addSubMult(x: Int, y:Int) : (Int, Int, Int) = {
...
(x + y, x - y, x * y)
}
</syntaxhighlight>
</lang>
You can use pattern matching to extract the components:
<langsyntaxhighlight lang="scala">val (sum, difference) = addsub(33, 12)</langsyntaxhighlight>
Scala borrows this idea from ML, and generalizes it into [http://www.scala-lang.org/node/112 extractors].
 
=={{header|Scheme}}==
Scheme can return multiple values using the <code>values</code> function, which uses continuations:
<langsyntaxhighlight lang="scheme">(define (addsub x y)
(values (+ x y) (- x y)))</langsyntaxhighlight>
You can use the multiple values using the <code>call-with-values</code> function:
<langsyntaxhighlight lang="scheme">(call-with-values
(lambda () (addsub 33 12))
(lambda (sum difference)
(display "33 + 12 = ") (display sum) (newline)
(display "33 - 12 = ") (display difference) (newline)))</langsyntaxhighlight>
The syntax is kinda awkward. SRFI 8 introduces a <code>receive</code> construct to make this simpler:
<langsyntaxhighlight lang="scheme">(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))</langsyntaxhighlight>
SRFI 11 introduces a <code>let-values</code> construct to make this simpler:
<langsyntaxhighlight lang="scheme">(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))</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight Seed7lang="seed7">$ include "seed7_05.s7i";
 
const proc: sumAndDiff (in integer: x, in integer: y, inout integer: sum, inout integer: diff) is func
Line 2,448 ⟶ 3,106:
writeln("Sum: " <& sum);
writeln("Diff: " <& diff);
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,458 ⟶ 3,116:
=={{header|SenseTalk}}==
You can return multiple values in SenseTalk by returning a list, which can be assigned to multiple variables.
<langsyntaxhighlight lang="sensetalk">set [quotient,remainder] to quotientAndRemainder(13,4)
 
put !"The quotient of 13 ÷ 4 is: [[quotient]] with remainder: [[remainder]]"
Line 2,464 ⟶ 3,122:
to handle quotientAndRemainder of num, divisor
return [num div divisor, num rem divisor]
end quotientAndRemainder</langsyntaxhighlight>
{{out}}
<pre>
Line 2,471 ⟶ 3,129:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func foo(a,b) {
return (a+b, a*b);
}</langsyntaxhighlight>
 
Catching the returned arguments:
<langsyntaxhighlight lang="ruby">var (x, y) = foo(4, 5);
say x; #=> 9
say y; #=> 20</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 2,484 ⟶ 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):
 
<langsyntaxhighlight lang="smalltalk">foo multipleValuesInto:[:a :b |
Transcript show:a; cr.
Transcript show:b; cr.
]</langsyntaxhighlight>
 
or:
<langsyntaxhighlight lang="smalltalk">|val1 val2|
foo multipleValuesInto:[:a :b |
val1 := a.
Line 2,496 ⟶ 3,154:
].
... do something with val1 and val2...
</syntaxhighlight>
</lang>
 
The called method in foo looks like:
<langsyntaxhighlight lang="smalltalk">
multipleValuesInto: aTwoArgBlock
...
aTwoArgBlock value:<value1> value:<value2>
</syntaxhighlight>
</lang>
i.e. it invokes the passed-in lambda closure with the two (return-)values.
 
=={{header|Standard ML}}==
Every function returns one value. The conventional way to return multiple values is to return a tuple.
<langsyntaxhighlight lang="sml">fun addsub (x, y) =
(x + y, x - y)</langsyntaxhighlight>
You can use pattern matching to extract the components:
<langsyntaxhighlight lang="sml">let
val (sum, difference) = addsub (33, 12)
in
print ("33 + 12 = " ^ Int.toString sum ^ "\n");
print ("33 - 12 = " ^ Int.toString difference ^ "\n")
end</langsyntaxhighlight>
 
=={{header|Swift}}==
Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple.
<langsyntaxhighlight lang="swift">func addsub(x: Int, y: Int) -> (Int, Int) {
return (x + y, x - y)
}</langsyntaxhighlight>
You can use pattern matching to extract the components:
<langsyntaxhighlight lang="swift">let (sum, difference) = addsub(33, 12)
println("33 + 12 = \(sum)")
println("33 - 12 = \(difference)")</langsyntaxhighlight>
 
=={{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.)
<langsyntaxhighlight lang="tcl">proc addsub {x y} {
list [expr {$x+$y}] [expr {$x-$y}]
}</langsyntaxhighlight>
This can be then assigned to a single variable with <code>set</code> or to multiple variables with <code>lassign</code>.
<langsyntaxhighlight lang="tcl">lassign [addsub 33 12] sum difference
puts "33 + 12 = $sum, 33 - 12 = $difference"</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 2,541 ⟶ 3,199:
 
The following function potentially returns three values, which will happen if called with three arguments, each of which is an unbound variable:
<langsyntaxhighlight lang="txr">@(define func (x y z))
@ (bind w "discarded")
@ (bind (x y z) ("a" "b" "c"))
@(end)</langsyntaxhighlight>
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:
<syntaxhighlight lang ="txr">@(func t r s)</langsyntaxhighlight>
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"):
<langsyntaxhighlight lang="txr">@(func "1" r s)</langsyntaxhighlight>
Successful call binding only one new variable:
<langsyntaxhighlight lang="txr">@(func "a" "b" s)</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 2,560 ⟶ 3,218:
it can be simulated through some clunky code.
 
<langsyntaxhighlight lang="bash">
#!/bin/sh
funct1() {
Line 2,575 ⟶ 3,233:
echo "x=$x"
echo "y=$y"
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,587 ⟶ 3,245:
 
This example gets a specified amount of strings from the user, then returns a stream containing them.
<langsyntaxhighlight lang="ursa">def getstrs (int n)
decl string<> input
 
Line 2,606 ⟶ 3,264:
set ret (getstrs amount)
 
out endl ret endl console</langsyntaxhighlight>
{{out}}
<pre>how many strings do you want to enter? 5
Line 2,619 ⟶ 3,277:
=={{header|VBA}}==
Firt way : User Defined Type
<syntaxhighlight lang="vb">
<lang vb>
Type Contact
Name As String
Line 2,639 ⟶ 3,297:
Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old."
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>SMITH John, 23 years old.</pre>
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
Divide = True
Line 2,665 ⟶ 3,323:
Debug.Print "Divide return : " & B & " Result = " & R
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>Divide return : True Result = 3,33333333333333
Divide return : False Result = 1,#INF</pre>
Third way : ParramArray
<syntaxhighlight lang="vb">
<lang vb>
Function Multiple_Divide(Dividend As Integer, Divisor As Integer, ParamArray numbers() As Variant) As Long
Dim i As Integer
Line 2,705 ⟶ 3,363:
Next i
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>The function return : 1
Line 2,721 ⟶ 3,379:
vbNullString</pre>
Fourth way : the variant() function
<syntaxhighlight lang="vb">
<lang vb>
Function List() As String()
Dim i&, Temp(9) As String
Line 2,740 ⟶ 3,398:
Next
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>Liste 1
Line 2,754 ⟶ 3,412:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
*!* Return multiple values from a function
*!* The simplest way is to pass the parameters by reference
Line 2,772 ⟶ 3,430:
RETURN n
ENDFUNC
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight ecmascriptlang="wren">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]).")</langsyntaxhighlight>
 
{{out}}
Line 2,787 ⟶ 3,445:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
proc Rect2Polar(X,Y,A,D); \Return two polar coordinate values
Line 2,800 ⟶ 3,458:
RlOut(0, Dist);
CrLf(0);
]</langsyntaxhighlight>
 
{{out}} (angle is in radians):
Line 2,806 ⟶ 3,464:
0.64350 5.00000
</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}}==
<langsyntaxhighlight lang="zkl">fcn f{return(1,2,"three")}
a,b,c:=f() // a==1, b==2, c=="three"</langsyntaxhighlight>
Anonymous user