⚠️ Warning: This is a draft ⚠️

This means it might contain formatting issues, incorrect code, conceptual problems, or other severe issues.

If you want to help to improve and eventually enable this page, please fork RosettaGit's repository and open a merge request on GitHub.

{{task|Basic language learning}} [[Category:Functions and subroutines]] {{omit from|GUISS}}

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

## 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))
```

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.

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

```

{{out}}

```
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|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 ) )
)
```

{{out}}

```
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.
```

## ANSI Standard 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
```

## ATS

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

```//
#include
//
(* ****** ****** *)

(
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.

```
Local \$aReturn
\$aReturn = \$iX + \$iY
\$aReturn = \$iX - \$iY
Return \$aReturn
EndFunc

```

=

## BaCon

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

```' Return multiple values
RECORD multi
LOCAL num
LOCAL s\$
END RECORD

FUNCTION f(n) TYPE multi_type
LOCAL r = { 0 } TYPE multi_type
r.num = n
r.s\$ = "Hitchhiker's Guide"
RETURN r
END FUNCTION

DECLARE rec TYPE multi_type
rec = f(42)
PRINT rec.num
PRINT rec.s\$
PRINT rec.s\$
```

{{out}}

```prompt\$ ./return-multiple
42
Hitchhiker's Guide
```

=

## 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
```

==={{header|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

```

## Bracmat

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

```bracmat
```

You can use pattern matching to extract the components:

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

{{out}}

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

{{out}}

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

{{out}}

```The name's Bond. James Bond.

```

## 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" ;
}
```

{{out}}

`The smallest number is -10, the biggest 987!`
## 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. ```c sharp 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 nums, out int max, out int min) { var sortedNums = nums.OrderBy(num => num).ToArray(); max = sortedNums.Last(); min = sortedNums.First(); } } ``` {{out}} ```txt Min: -3 Max: 51 ``` ## Clipper Every function returns one value. The conventional way to return multiple values is to bundle them into an array. ```Clipper 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 [http://blog.jayfields.com/2010/07/clojure-destructuring.html destructuring]. ```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)) ``` In complex cases, it would make more sense to return a map, which can be destructed in a similar manner. ```clojure (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)) ``` ## CMake ```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}} ```COBOL 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. ``` {{out}} ```txt 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. ```lisp (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: ```lisp (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: ```lisp > (defun add-sub (x y) (values-list (list (+ x y) (- x y)))) ADD-SUB > (add-sub 4 2) ; 6 (primary) and 2 6 ; 2 > (add-sub 3 1) ; 4 (primary) and 2 4 ; 2 > (+ (add-sub 4 2) (add-sub 3 1)) ; 6 + 4 10 > (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`: ```lisp (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: ```lisp (values (values 1 2 3) (values) 'a) ``` yields three values: ```txt -> 1; NIL; A ``` This also means that `values` can be used to reduce a multiple value to a single value: ```lisp ;; 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: ```lisp (multiple-value-bind (dividend remainder) (truncate 16 3) ;; in this scope dividend is 5; remainder is 1 ) ``` 2. Conversion to a list: ```lisp (multiple-value-list (truncate 16 3)) ;; yields (5 1) ``` 3. Reification of multiple values as arguments to another function: ```lisp ;; pass arguments 5 1 to +, resulting in 6: (multiple-value-call #'+ (truncate 16 3)) ``` 4. Assignment to variables: ```lisp ;; 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: ```lisp (setf (values dividend remainder) (truncate 16 1)) ``` ## D ```d import std.stdio, std.typecons, std.algorithm; mixin template ret(string z) { mixin({ string res; auto r = z.split(" = "); auto m = r.split(", "); auto s = m.join("_"); res ~= "auto " ~ s ~ " = " ~ r ~ ";"; 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); } ``` {{out}} ```txt 33 + 12 = 45 33 - 12 = 21 ``` ## Dc Define a divmod macro `~` which takes `a b` on the stack and returns `a/b a%b`. ```dc [ S1 S2 l2 l1 / L2 L1 % ] s~ 1337 42 l~ x f ``` {{out}} ```txt 35 31 ``` =={{header|Déjà Vu}}== ```dejavu function-returning-multiple-values: 10 20 !print !print function-returning-multiple-values ``` {{out}} ```txt 10 20 ``` =={{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 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: ```Dyalect func divRem(x, y) { (x / y, x % y) } ``` ## EchoLisp One can return the result of the '''values''' function, or a list. ```scheme (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. ```Eiffel 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. ```Eiffel 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 4.1 : ```elena 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) } ``` {{out}} ```txt Min: -3 Max: 51 ``` ## Elixir Elixir returns in the tuple form when returning more than one value. ```elixir 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}" ``` {{out}} ```txt Add: 11, Sub: 3 ``` ## Erlang ```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}. ``` {{out}} ```txt 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. ```ERRE 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 ``` ## Euphoria Any Euphoria object can be returned. A sequence of objects can be returned, made from multiple data types as in this example. ```euphoria 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) + third & (first * second * third) * third --..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() ``` {{out}} ```txt {9.999999,23.999988} Press Any Key to continue... ``` =={{header|F_Sharp|F#}}== A function always returns exactly one value. To return multiple results, they are typically packed into a tuple: ```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 ``` 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. ```factor 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 ```false [\\$@\$@*@@/]f: { in: a b, out: a*b a/b } 6 2f;! .` ,. { 3 12 } ``` =={{header|Fōrmulæ}}== In [http://wiki.formulae.org/Return_multiple_values this] page you can see the solution of this task. Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). 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 transportation effects more than visualization and edition. The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code. ## 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.). ```forth : muldiv ( a b -- a*b a/b ) 2dup / >r * r> ; ``` ## Fortran {{trans|Haskell}} ```Fortran 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 ```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 ``` {{out}} ```txt 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. ```frink divMod[a, b] := [a div b, a mod b] [num, remainder] = divMod[10, 3] ``` ## FunL {{trans|Scala}} ```funl def addsub( x, y ) = (x + y, x - y) val (sum, difference) = addsub( 33, 12 ) println( sum, difference, addsub(33, 12) ) ``` {{out}} ```txt 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: ```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 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 is interchangeable with Len(string) letterCount.nil& = strIn + s 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." ``` Output: ```txt 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): 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 // Pass address of global array to fill it 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 ``` Output: ```txt 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: include "ConsoleWindow" // Elements in global array _maxDim = 3 begin globals dim as 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 ) ) 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 ``` Output: ```txt 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. 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 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 ``` Output: ```txt 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 ``` ## Go Functions can return multiple values in Go: ```go func addsub(x, y int) (int, int) { return x + y, x - y } ``` Or equivalently using named return style: ```go 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: ```go sum, difference := addsub(33, 12) fmt.Printf("33 + 12 = %d\n", sum) fmt.Printf("33 - 12 = %d\n", difference) ``` ## Groovy In Groovy functions return one value. One way to return multiple ones is to use anonymous maps as a sort of tuple. ```groovy def addSub(x,y) { [ sum: x+y, difference: x-y ] } ``` Result: ```groovy 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: ```groovy 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. ```visualfoxpro FUNCTION Addsub( x, y ) RETURN { x + y, x - y } ``` ## Haskell Every function returns one value. The conventional way to return multiple values is to return a tuple. ```haskell addsub x y = (x + y, x - y) ``` You can use pattern matching to extract the components: ```haskell main = do let (sum, difference) = addsub 33 12 putStrLn ("33 + 12 = " ++ show sum) putStrLn ("33 - 12 = " ++ show difference) ``` =={{header|Icon}} and {{header|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: ```Icon 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. ```j 1 2+3 4 4 6 ``` ## Java {{trans|NetRexx}} ```Java 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); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args); sv_ = args; break; default: nv_ = Long.parseLong(args); sv_ = args; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair 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