Search code examples
pythonfunctionlanguage-agnosticlanguage-designsyntactic-sugar

Elegant ways to return multiple values from a function


It seems like in most mainstream programming languages, returning multiple values from a function is an extremely awkward thing.

The typical solutions are to make either a struct or a plain old data class and return that, or to pass at least some of the parameters by reference or pointer instead of returning them.

Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass.

The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity.

Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.

The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:

a, b = foo(c)  # a and b are regular variables.
myTuple = foo(c)  # myTuple is a tuple of (a, b)

Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.


Solution

  • Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial.

    For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it)

    typedef boost::tuple<double,double,double> XYZ;
    
    XYZ foo();
    
    double x,y,z;
    boost::tie(x,y,z) = foo();
    

    or a less contrived example

    MyMultimap::iterator lower,upper;
    boost::tie(lower,upper) = some_map.equal_range(key);