Fortran中结果变量的用途是什么? [英] What is the purpose of result variables in Fortran?

查看:196
本文介绍了Fortran中结果变量的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Fortran中,有两种标准方法可以从函数返回结果。第一个是将函数的返回值赋给函数名。

 函数foo()
整数:: foo

foo = 10
结束函数foo

第二种形式,在Fortran 90中标准化是通过一个result变量。

  function foo result(res)
integer :: res

res = 10
end function foo

调用函数的任何一种形式都会返回值10.我的问题是,Fortran 90委员会介绍结果变量的基本原理是什么?他们是否将普遍的做法标准化?或者他们允许程序通过不将函数名称绑定到函数结果而更加模块化。例如,在第二个版本的 foo()中,函数 foo()的名称可以更改为 bar()并且该函数在调用时仍然可以按预期工作。



然而,我可能是错的。有人知道引入结果变量的实际原理是什么吗?

解决方案

结果递归。在讨论递归函数的作用之前,先澄清一下结果变量是什么。



函数结果总是通过结果变量返回,无论是 result 是否被使用 1 使用 result 结果变量具有指定的名称,没有它结果变量与函数具有相同的名称。在后一种情况下,名称的使用是对结果变量的引用,而不是函数。

因此,如果函数 foo 结果变量 foo 那么我们不能直接递归:

 递归函数foo(n)
foo = foo(n-1)!哦,亲爱的
结束功能

结果出现,以便我们可以有

$ $ p $ code递归函数foo(n)结果(res)
res = foo( n-1)! Yay
最终功能






[1]那么,直到2008年,当变量的定义发生变化时,这才是真实的。对于现代Fortran,而不是术语函数结果


In Fortran, there are two standard ways to return a result from a function. The first one is by assigning the return value of the function to the function name.

function foo()
    integer :: foo

    foo = 10
end function foo

The second form, standardized in Fortran 90 is through a "result" variable.

function foo result(res)
    integer :: res

    res = 10
 end function foo

Calling either form of the function returns the value 10. My question is, what was the rationale of the Fortran 90 committee for introducing result variables? Were they standardizing a common practice? Or were they allowing programs to be more modular by not tying the function name to a function result. For example, in the second version of foo(), the name of the function foo() could be changed to bar() and the function would still work as expected when called.

However, I may be wrong. Does anyone know what the actual rationale was for introducing result variables?

解决方案

Introduced at the same time as the result was recursion. Before we get to how a recursive function comes about, some clarification on what a result variable is.

The function result is always returned through a result variable, whether result is used or not.1 With result the result variable has the name specified, and without it the result variable has the same name as the function. In this latter case use of the name is a reference to the result variable and not the function.

So, if the function foo has result variable foo then we can't do direct recursion:

recursive function foo(n)
  foo = foo(n-1) ! Oh dear
end function

result comes about so that we can have

recursive function foo(n) result(res)
  res = foo(n-1) ! Yay
end function


[1] Well, this is true up until Fortran 2008, when the definition of variable changed. For modern Fortran use instead the term function result.

这篇关于Fortran中结果变量的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆