Return multiple values: Difference between revisions

add BLC solution
imported>Tromp
(add BLC solution)
 
(20 intermediate revisions by 13 users not shown)
Line 280:
end.</syntaxhighlight>
 
=={{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="ansi standard basicc">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</syntaxhighlight>
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}}==
Line 365 ⟶ 398:
 
=={{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.
Line 414 ⟶ 467:
150 LET C=A+B:LET D=A-B
160 END DEF</syntaxhighlight>
==={{header|uBasic/4tH}}===
{{Trans|Forth}}
uBasic/4tH shares many features with Forth - like a stack. Parameters of functions and procedures are passed through this stack, so there is no difference between pushing the values on the stack ''or'' passing them as function parameters. Return values are passed by the stack as well, so if we push additional values ''before'' calling '''RETURN''' we can retrieve them using '''POP()'''.
<syntaxhighlight lang="qbasic">a = FUNC (_MulDiv (33, 11))
b = Pop()
 
Print "a * b = ";a, "a / b = ";b
 
Push 33, 11 : Proc _MulDiv
a = Pop() : b = Pop()
 
Print "a * b = ";a, "a / b = ";b
End
 
_MulDiv
Param (2)
 
Push a@ / b@
Return (a@ * b@)</syntaxhighlight>
{{Out}}
<pre>a * b = 363 a / b = 3
a * b = 363 a / b = 3
 
0 OK, 0:226 </pre>
 
=={{header|Binary Lambda Calculus}}==
In the lambda calculus, one can return a tuple, which when applied to a function f, applies f to all the tuple elements. For example, <A,B,C> is <code>\f.f A B C</code>. Alternatively, one can use continuation-passing-style (cps), in which the function f is not applied the tuple return value, but instead is passed as an extra initial argument, and then the function can return f applied to the multiple values.
 
=={{header|BQN}}==
Line 497 ⟶ 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.
<syntaxhighlight lang="c sharp">using System;
using System.Collections.Generic;
Line 890 ⟶ 970:
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
funcproc addSubtract a b . sum diff .
sum = a + b
diff = a - b
.
call addSubtract 7 5 sum diff
print "Sum: " & sum
print "Difference: " & diff
Line 949 ⟶ 1,029:
 
=={{header|Elena}}==
ELENA 56.0x :
<syntaxhighlight lang="elena">import system'routines;
import extensions;
Line 971 ⟶ 1,051:
console.printLine("Min: ",min," Max: ",max)
}</syntaxhighlight>
=== Using Tuples syntax ===
<syntaxhighlight lang="elena">import system'routines;
import extensions;
extension op
{
::(int, int) MinMax()
{
var ordered := self.ascendant();
^ (ordered.FirstMember, ordered.LastMember);
}
}
public program()
{
var values := new int[]{4, 51, 1, -3, 3, 6, 8, 26, 2, 4};
(int min, int max) := values.MinMax();
console.printLine("Min: ",min," Max: ",max)
}</syntaxhighlight>
{{out}}
Line 1,032 ⟶ 1,134:
<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'''
<syntaxhighlight lang="euler">
'''new''' mv; '''new''' getMV;
begin
new mv; new getMV;
getMV &lt;- ` '''formal''' v; ( v, v * v, v * v * v ) &apos;;
 
getMV <- ` formal v; ( v, v * v, v * v * v ) ';
mv &lt;- getMV( 3 );
 
mv <- getMV( 3 );
'''out''' mv[ 1 ];
 
'''out''' mv[ 12 ];
'''out''' mv[ 23 ];
'''end''' $
out mv[ 3 ]
end $
</syntaxhighlight>
 
=={{header|Euphoria}}==
Line 1,218 ⟶ 1,318:
Here is an example of returning multiple values using pointers:
<syntaxhighlight 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."
 
HandleEvents
</syntaxhighlight>
 
Line 1,249 ⟶ 1,349:
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,281 ⟶ 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
 
HandleEvents
</syntaxhighlight>
 
Line 1,299 ⟶ 1,398:
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,311 ⟶ 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,325 ⟶ 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
 
HandleEvents
</syntaxhighlight>
 
Line 1,344 ⟶ 1,443:
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,390 ⟶ 1,487:
// Check the new results
print gC1 : print gC2
 
HandleEvents
</syntaxhighlight>
 
Line 1,415 ⟶ 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'''
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.
 
Every function returns one value. The conventional way to return multiple values is to return a list.
In '''[https://formulae.org/?example=Return_multiple_values this]''' page you can see the program(s) related to this task and their results.
 
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]]
 
[[File:Fōrmulæ - Return multiple values 03.png]]
 
=={{header|Go}}==
Line 1,597 ⟶ 1,704:
 
=={{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}}
<syntaxhighlight lang="java">import java.util.List;
Line 1,881 ⟶ 2,023:
s, d = addsub( 7, 5 )
print( s, d )</syntaxhighlight>
 
 
 
=={{header|M2000 Interpreter}}==
Functions can be made in 5 ways: Normal, Lambda, Simple, Group which return value, Pointer to Group which return value. For every way we can return multiple values as tuple (in a mArray type of array). The (a,b)=funcA() is a way to define/assign values from tuple. So (a,b)=(1, 2) is the simple form. A return value from a function done using = as statement. This return isn't the last statement (isn't exit from function), so may we have multiple = as statements and the last one which we execute return the value. By default if we don't use the = statement based on function's suffix at name (at call) we get 0 or "". Functions can return any type of types. So the return type based on statement = (or the interpreter return 0 or "" based on name at call, where suffix $ means we return empty string, although later versions of language can return string/ make string variables without suffix $).
 
<syntaxhighlight lang="m2000 interpreter">
module Return_multiple_values{
Print "Using a function"
function twovalues(x) {
="ok", x**2, x**3
}
// this is a sugar syntax to apply a tuple (mArray type) to variables
// can be new variables or pre defined
// if they are predifined then overflow may happen
byte b
// object a=(,) // if a is an object we can't assign number
(s, a,b)=twovalues(3) // twovalues(30) raise overflow
Print a=9, b=27, s="ok"
c=twovalues(3)
// need to use val$() because val() on string type is like a Val("1233")
Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
// we can pass by reference
callbyref(&twovalues())
sub callbyref(&a())
local a, b, s as string
(s, a,b)=a(3)
Print a=9, b=27, s="ok"
end sub
}
Return_multiple_values
// modules may change definitions like functions (but not subs and simple functions)
Module Return_multiple_values{
// lambdas are first citizens, can be called as functions or used as variables/values
Print "Using lambda function"
twovalues=lambda (x) ->{
="ok", x**2, x**3
}
byte b
(s, a,b)=twovalues(3) // twovalues(30) raise overflow
Print a=9, b=27, s="ok"
c=twovalues(3)
Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
callbyref(&twovalues())
callbyValue(twovalues, 3)
sub callbyref(&a())
local a, b, s as string
(s, a,b)=a(3)
Print a=9, b=27, s="ok"
end sub
sub callbyValue(g, v)
local a, b, s as string
(s, a,b)=g(v)
Print a=9, b=27, s="ok"
end sub
}
Return_multiple_values
module Return_multiple_values{
Print "Using simple function (static)"
byte b
(s, a,b)=@twovalues(3) // twovalues(30) raise overflow
Print a=9, b=27, s="ok"
c=@twovalues(3)
Print c#val$(0)="ok", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
function twovalues(x)
="ok", x**2, x**3
end function
}
Return_multiple_values
module Return_multiple_values {
// a group may used as function too
// we can use fields to alter state
// we can't pass the object as function by reference
// but we can pass an object function
// group is a static object to this module
// in every call of this module, this object initialised
// when the group statement executed
// and destroyed at the end of execution without a call to remove destructor
Print "Using a group as a function with a field"
group twovalues {
rep$="ok"
function forRef(x) {
=.rep$, x**2, x**3
}
value () { // ![] pass the stack of values to forRef function
if empty then =this: exit
=.forRef(![]) // or use =.rep$, x**2, x**3 and (x) at value
}
Set {
Error "no object change allowed"
}
}
byte b
// object a=(,) // if a is an object we can't assign number
(s, a,b)=twovalues(3)
Print a=9, b=27, s="ok"
twovalues.rep$="Yes"
c=twovalues(3)
// need to use val$() because val() on string type is like a Val("1233")
Print c#val$(0)="Yes", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
callbyref(&twovalues.forRef())
callbyValue(twovalues, 3)
sub callbyref(&a())
local a, b, s as string
(s, a,b)=a(3)
Print a=9, b=27, s="Yes"
end sub
sub callbyValue(g, v)
local a, b, s as string
(s, a,b)=g(v)
Print a=9, b=27, s="Yes"
end sub
}
Return_multiple_values
 
module Return_multiple_values {
Print "Using a pointer to group as a function with a field (group created by a Class)"
class iTwovalues {
string rep
function forRef(x) {
=.rep, x**2, x**3
}
value () { // ![] pass the stack of values to forRef function
=.forRef(![])
}
Set {
Error "no object change allowed"
}
// optional here, only to return the destriyed event (after the module exit from execution)
remove {
print .rep+" destroyed"
}
class:
Module iTwovalues (.rep) {
}
}
byte b
// twovalues is a pointer to an object of general type Group
twovalues->iTwovalues("ok")
Print twovalues is type iTwovalues = true
(s, a,b)=Eval(twovalues, 3)
Print a=9, b=27, s="ok"
twovalues=>rep="Yes"
c=twovalues=>forRef(3) // better to call a function instead of use Eval()
Print c#val$(0)="Yes", c#val(1)=9, c#val(2)=27, type$(c)="mArray"
for twovalues {
// we have to use for object { } to use references to members of object
callbyref(&.forRef())
}
// if we hide the next statement we will see Yes destroyed after return from this module (before "done")
twovalues=pointer() // because twovalues is the last pointer to object, the object destroyed
// we see now: Yes destroyed
sub callbyref(&a())
local a, b, s as string
(s, a,b)=a(3)
Print a=9, b=27, s="Yes"
end sub
}
Return_multiple_values
Print "Done"
</syntaxhighlight>
 
=={{header|Maple}}==
Line 2,447 ⟶ 2,751:
 
=={{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.
<syntaxhighlight 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.</syntaxhighlight>
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>
 
Line 3,104 ⟶ 3,434:
=={{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.
<syntaxhighlight lang="ecmascriptwren">var splitName = Fn.new { |fullName| fullName.split(" ") }
 
var names = splitName.call("George Bernard Shaw")
Anonymous user