Search code examples
language-agnosticprogramming-languageslanguage-design

Efficient implementation of multiple return values?


Is it possible to implement efficiently (with little to no runtime overhead) functions that return multiple vales / a tuple type?

In a C-like language something like this:

int, float f(int a) {
  return a*2 , a / 2;
}

Is there a reason why very few statically compiled languages do this?


Solution

  • Yes, it can be efficient. You may need to spill registers, but it is possible.

    GHC for example, implements the "constructed product return" optimization, that:

    determines when a function can profitably return multiple results in registers. The analysis is based only on a function's definition, and not on its uses (so separate compilation is easily supported) and the results of the analysis can be expressed by a transformation of the function definition alone.

    CPR is a huge win for returning small structures (i.e. tuples, tagged unions).

    More information: