Search code examples
return-valueprogramming-languagesnaming-conventions

Do any programming languages provide the ability to name the return value of a function?


Quite commonly while programming I find it necessary to document the value that a function returns. In Java/Scala world, you often use comments above the function to do this.

However, this can stand out in contrast to the first-class documentation that function parameters get in all languages. For example:

def exponent(base: Int, power: Int): Int

Here we have the signature for a method that raises base to the power power and returns... probably the result of that computation? I know for certain it returns an Int, and it seems quite reasonable to infer that the return value is indeed the result of calculating base ^ power, but in many functions I've written and read it is not possible to infer the return value's semantic meaning quite so easily and you need to study the documentation and/or actually use the method to find out.

Which leads me to wonder, do any languages provide support for optionally declaring a semantic name for the return value?

def exponent(base: Int, power: Int): Int(exitCode)

A hah! Turns out this function actually returns an indication of whether the operation succeeded or failed! Look it is so clear right there in the method signature! My IDE could also intelligently create a variable with the same name when I call this method, a la:

// Typing in IntelliJ
exponent(5, 5)<TAB>

// Autocompletes to:
val exitCode = exponent(5, 5)

I'm not under any illusion that this is some sort of ground-breaking idea, but it seems like it could be generally useful, and I'm struck that I have never seen this concept implemented in any programming language.

Can you name any single programming language that does have this kind of semantic naming of return values?


Solution

  • In APL, for instance, the result of a function is declared as a variable. The function declaration in your example could be written like

    exitCode ← base exponent power
    

    in APL. However, a function with no side effects should always be named after the result it returns. If the function can fail I would use a value that is never returned on success, for instance -1 in this case.