Return multiple values: Difference between revisions
Content added Content deleted
(J) |
(added php and python) |
||
Line 24: | Line 24: | ||
<lang j> 1 2+3 4 |
<lang j> 1 2+3 4 |
||
4 6</lang> |
4 6</lang> |
||
=={{header|PHP}}== |
|||
Every function returns one value. The conventional way to return multiple values is to bundle them into an array. |
|||
<lang php>function addsub($x, $y) { |
|||
return array($x + $y, $x - $y); |
|||
}</lang> |
|||
You can use the <code>list()</code> construct to assign to multiple variables: |
|||
<lang php>list($sum, $difference) = addsub(33, 12); |
|||
echo "33 + 12 = $sum\n"; |
|||
echo "33 - 12 = $difference\n";</lang> |
|||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
Line 36: | Line 49: | ||
[int z, int w] = addsub(5,4); |
[int z, int w] = addsub(5,4); |
||
</lang> |
</lang> |
||
=={{header|Python}}== |
|||
Every function returns one value. The conventional way to return multiple values is to bundle them into a tuple. |
|||
<lang python>def addsub(x, y): |
|||
return x + y, x - y</lang> |
|||
(Note that parentheses are not necessary for a tuple literal in Python.) |
|||
You can assign to a comma-separated list of targets: |
|||
<lang python>sum, difference = addsub(33, 12) |
|||
print "33 + 12 = %s" % sum |
|||
print "33 - 12 = %s" % difference</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |