Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 433
user318904 Avatar asked Aug 11 '26 19:08

user318904


1 Answers

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:

  • CPR analysis in GHC.
  • More on demand analysis.
like image 135
Don Stewart Avatar answered Aug 14 '26 11:08

Don Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!