简体   繁体   English

是否有任何编程语言提供命名 function 的返回值的能力?

[英]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.在编程时,我经常发现有必要记录 function 返回的值。 In Java/Scala world, you often use comments above the function to do this.在 Java/Scala 世界中,您经常使用 function 上方的注释来执行此操作。

However, this can stand out in contrast to the first-class documentation that function parameters get in all languages.然而,这与 function参数在所有语言中获得的一流文档相比可以脱颖而出。 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 ?这里我们有一个方法的签名,该方法将base提高到power并返回......可能是该计算的结果 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.我确定它返回一个Int ,并且推断返回值确实是计算base ^ power的结果似乎很合理,但在我写过和读过的许多函数中,不可能推断出返回值的语义这意味着非常容易,您需要研究文档和/或实际使用该方法来找出答案。

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!哈,原来这个 function 实际上返回了操作成功或失败的指示:看,它在方法签名中非常清楚! My IDE could also intelligently create a variable with the same name when I call this method, a la:我的 IDE 也可以在我调用这个方法时智能地创建一个同名的变量,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?你能说出任何一种具有这种返回值语义命名的编程语言吗

In APL, for instance, the result of a function is declared as a variable.例如,在 APL 中,function 的结果被声明为一个变量。 The function declaration in your example could be written like您示例中的 function 声明可以这样写

exitCode ← base exponent power

in APL.在APL。 However, a function with no side effects should always be named after the result it returns.但是,没有副作用的 function 应始终以其返回的结果命名。 If the function can fail I would use a value that is never returned on success, for instance -1 in this case.如果 function 可能会失败,我会使用一个在成功时永远不会返回的值,例如本例中的 -1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM