views:

718

answers:

14

Why do functions in some popular languages return only a single result?

+9  A: 

To simplify matter.

You can always return a T[], Pair<L,R>, Set<E>, etc in these languages to emulate returning multiple values. That takes care of most multiple return values scenarios out there.

It's not worth changing the semantics of the language so much for a gain so little.

Related questions

polygenelubricants
True you can always return object which contains varied variables. But the question still remain why where they thought to do so? return just one value.
sushil bharwani
@sushil: because what you're asking amounts to syntactic sugars, and while there's nothing inherently wrong in careful attempts to sweeten up a language, there are also arguments for a simpler, plain, practical language.
polygenelubricants
There are arguments for a simpler language. I do not think these arguments were the primary driving force behind languages like C++. :-)
Ken
+18  A: 

A function (in languages you mentioned in your tags) does have a single output , but that output does not have to be a single value. Your output can easily be a class which encapsulates any amount of data you want.

Also, note that you can also pass multiple input arguments by reference to your function, thereby increasing the number of returned outputs.

Groo
And note that functional languages have a single *input* too. Currying or passing tuples is as artificial as returning a tuple or a function.
Alexandre C.
@Alex: +1 from me, god how I love Haskell's implicit currying :)
FredOverflow
-1 This is not a answer to the question, but a comment.
OscarRyz
Returning object of a class does not mean returning multiple values. Object still represents one value (reference to that object).
sbidwai
A: 

How would you call such a function?

Brainfart:

int int Get2Ints();
{
  return 1, 2;
}

int a,b =  Get2Ints();

Very unlogical. You will get the same effect using references (and only 1 return)

PoweRoy
It just a brainfart people ;)
PoweRoy
I'd hardly call it illogical. Quite useful to me.
GMan
@GMan, it is illogical. `long long f() { return 1,2; }` works fine for me in g++ :) Why there should be different behavior for hypothetical `int int` ?
Kirill V. Lyadvinsky
@Kirill: Haha, well obviously syntax and language would change, but I mean the idea is nice.
GMan
Just for fun: http://codepad.org/fcYCtYXy
Kirill V. Lyadvinsky
-1, If your language doesn't provide some feature, it doesn't mean the feature is illogical. Here are some examples of the languages that provide this feature: http://ideone.com/ozaST (Scala), http://ideone.com/hwCbY (Python), http://ideone.com/znejb (OCaml).
missingfaktor
A: 

The function return an answer, why would it be designed to give more answers? And that answer can be any data structure you like so it could hold lots of values :)

aniri
+2  A: 

Google's Go supports multiple return values

Dennis Haarbrink
Erlang and Scala too : it is called tuples. I think we could find other languages with that feature, especially in the functionnal family.
Jean-Philippe Caruana
In Python, you can use implicit tuple unpacking such that if myfunc() returns a tuple, and you do a,b=myfunc(), a and b will take the appropriate values of the tuple.
John McCollum
in c++ too, it is called std::vector .. oh .. no .. it is called std::list .. even tuples are just "one value", it is one "object" which has subtypes. this question is not about which languages pretend to have more than one return value.
akira
The question was badly worded, see the update.
OscarRyz
+4  A: 

My best guess is that it carried over from mathematics. There you can have a function with multiple parameters, and value that's the result.

f(x1, x2, ...) = y (the formula might be something like x1 + x2^2 + x3^3 + ...)

Even if you want to map a multidimensional domain to a multidimensional range you usually write as:

f1(x1, x2, ...) = y1 (perhaps y1 = x1 + x2^1 + ... like above)
f2(x1, x2, ...) = y2 (and y2 = x1 - x2^2 + x3^3 - x4^4 +...)
...

since each y gets it's own mathematical formula based on the inputs, which in programming would just translate to multiple functions, it makes sense to separate it like this.

The problem is sometimes the formulas for y1 and y2 may be very similar or rely on iterating the same thing or whatnot, that doing them together might make more sense. In python you can do

return a1, a2;

and then call it like

x, y = f();

but in most languages you can only return one variable. That doesn't stop you from making it a complex object with multiple values included.

Andrei Fierbinteanu
Unfortunately functions in imperative languages have almost nothing to do with mathematical functions.
Philipp
I beg to differ, FORTRAN which is the oldest programming language stands for FORmula TRANslating or more exactly (as the first draft of the specification was called) 'The IBM <b>Mathematical Formula</b> Translating System'. Lisp which is the second oldest one was initially designed as 'a practical mathematical notation for computer programs' (from wikipedia). Mathematics have a lot to do with computer programs (or at least had in the early days).
Andrei Fierbinteanu
AFAIK, Python returns a single tuple object, and the syntactic sugar is the automatic unpacking of the tuple into separate variables. Tuples exist in C++ too (boost, tr1), except without syntactic sugar for unpacking. The C++ equivalent is: `tie(x, y) = f();`. C++0x adds syntactic sugar for constructing the tuple: `tuple<int, int> f() { return {1, 2}; }`
visitor
A: 

You can do this in perl:

sub foo
{
   return (10, 20);
}

my ($a, $b) = foo();  # sets $a to 10 and $b to 20

And similar constructs in other languages.

bluesmoon
can i know how these values are passed to calling function
sagar
sagar, the my ($a, $b) is your calling function, and the return (10, 20) is your called function. You simply return the entire list of items you want to return surrounded by parentheses, and on the caller's side, receive them in the same way.
bluesmoon
not really returning multiple values; any language can do that.
RCIX
+15  A: 

Functions return only one value because its the way "they" invented it in the old days of assembler. Basically what happens is that function pushes return value on the stack. Caller then pops the value from the stack. If function returned more values, caller wouldnt know how many values to pop and the stack would be unbalanced (leading to program crash).

Markos
+1 for being the only actual answer to the original question.
Coxy
That explains that assembler is like that, but there are languages with multiple return values (tuples) and support for direct boxing/unboxing --so that they can be directly used as if more than one element was being returned...
David Rodríguez - dribeas
But a tuple is only one value (that *contains* multiple values).
EricSchaefer
EricSchaefer: In some languages, that's true. In other languages (like Lisp Machine Lisp and Common Lisp), functions *do* return multiple values -- not tuples.
Ken
Note that in most common x86 binary calling conventions, return values aren't on the stack, but in the EAX register.
nikie
It would know the number of return values the same way it knows the number of arguments to pass. c++ example void f(int a) => 0 return values, one argument. c++ example 2 string ff() => return a string, 0 args. So why wouldn't int int f3() => 2 int returns and 0 arguments work? Well it does with pair<int,int> f3() => should return both values on the stack.
josefx
+1  A: 

I guess in most cases one return value is sufficient, and the mathematical notion of a function (or Lambda calculus) has one return value as well, so it's kind of understandable that language designers try to stick with the "standard". In fact having several functions which need multiple return values can be confusing and may be a sign of poor design, e.g. a missing compound class.

The "classical" approach for returning multiple values is using Tuples. Some languages have a built-in Tuple type (like Scala), but you can define it yourself in all languages that support type parameters in some form (templates, generics...). For Java, there is the nice JavaTuple lib.

Landei
A: 

It is to help reading source code. It's SOOOOO human-friendly this way! If this function would have more than one return value, this line could not be written:

 if (SomeFunction(a, b) != SUCCESS)
 {
    // do error handling
 }
Denes Tarjan
this is a call to a function
sagar
sure it is. :)this is a way you are using a function that returns one value.if it would return more values, you cannot use its return values in expressions as directly as this one.
Denes Tarjan
+1  A: 

A function has to fullfill a clearly defined task. Aside from the fact that you can always return an array: probably something was completely wrong with your softwaredesign if you'd need to return different values from different datatypes.

Besides that, it's much easier for a human to read a function with one return value.

ThemBones
+1  A: 

Lua does also support multiple return values: you can for example write the following:

function foo()
    return 1, 2, 3
end

a, b, c, d = foo()

after execution, a, b, c will hold the values 1, 2, 3 and d will be nil. You can in the same way do the following:

function bar()
   return true, 2, 3
end

if bar() then
   -- do something intelligent
end

the if statement will in this case only work with the first value returned - if you need the other values, you will have to store them in variables like usual:

a, b, c = bar()
if a then
   -- do something intelligent
end

so you see: in Lua, all the return values that are not needed are thrown away (like 2, 3 in the example with the if).

Henko
what about context switching for your answer
sagar
+1  A: 

Daniel Weinreb -- who worked on both Lisp dialects (which had multiple return values) and Java (which didn't), explains why:

When we added the multiple-value return feature to Lisp machine Lisp (from whence it went into Common Lisp), I believe that the desire to avoid consing was one of the serious motivations. Back then, we did not have good GC technology, and writing Lisp programs to carefully minimize consing was very common.

The other reason was for expressiveness: to make it clear that the function was really returning more than one result, rather than introducing a little list "type" (e.g. "a two-list of the file handle and a boolean to say whether...").

In Java, I've seen definitions of little classes whose only purpose is to be a way to return multiple values. The advantage of this approach is that the types and meanings of the returned values are documented (at least if you pick clear names and put in comments!). But it's rather verbose, in my opinion.

When I was first reviewing the early Java spec, I was surprised to see that there was no way to return multiple values. I wanted to lobby for adding that, so I tried to come up with a use case that was both simple and very compelling. I was unable to do so! So I didn't try lobbying for it. The designers of Java were pretty clearly trying to avoid a lot of bells and whistles (and syntactic sugar), and there's certainly a lot to be said for that.

Ken
what is effect of stack allocation on return value
sagar
There are a million strategies for implementing a Lisp compiler. According to #2f at http://groups.google.com/group/comp.lang.lisp/msg/96d32a463068044e Allegro passes them back in the same registers as args, Franz pushed them on the stack, and compilers using a C intermediary rely on less efficient methods. So probably anywhere from "zero" to "a lot" to "a meta layer on top of 'a lot'". :-)
Ken
A: 

I think the question is about memory allocation and stack organization The main thing is context switching at time of function call . the function frame is stored on the stack the frame contains function variables,general purpose registers and return values i know that much

sagar