PURE函数可以使用全局参数吗

PURE函数可以使用全局参数吗

本文介绍了Fortran PURE函数可以使用全局参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,对于使用函数式编程的人来说,在Fortran中所谓的纯函数还不够纯.所以这是我的问题.假设我有以下代码:

It seems to me the what is called a pure function in Fortran is not considered pure enough for those who use functional programming. So here is my question. Suppose I have the following code:

MODULE basics
  IMPLICIT NONE
  INTEGER, PARAMETER      :: dp = kind(1.0d0)
  REAL(dp), PARAMETER     :: PI=3.1415926535897932_dp
  REAL(dp), PARAMETER     :: earthEquatorialRadius=6378.137_dp
END MODULE basics

MODULE myFunctions
  USE basics
  IMPLICIT NONE

  PURE REAL(dp) FUNCTION sphericalArc(angleInRadians)
    REAL(dp),INTENT(IN)  :: angleInRadians

    sphericalArc= 2.0*PI*earthEquatorialRadius*angleInRadians
  END FUNCTION sphericalArc
END MODULE myFunctions

函数sphericalArc没有副作用,因此从这个意义上讲它是纯正的,但是它使用了全局常量.确实可以在函数内部定义参数PI和earthEquatorialRadius,但这是不可取的,因为我想在其他函数和子例程中使用它们.在每个函数或过程中定义dp类型将更加繁琐.

The function sphericalArc has no side effects, so it's pure in that sense, but it uses global constants. It's true that the parameters PI and earthEquatorialRadius can be defined inside the function but this is undesirable since I would like to use these in other functions and subroutines. It's going to be even more tedious to make the dp type defined in each function or procedure.

因此,从Fortran的角度来看,是一个使用在函数外部定义的全局参数的函数仍被认为是纯函数,可以从并发循环中调用它吗?

So from Fortran's perspective is a function that uses global parameters defined outside of the function still considered pure and can be called from a do concurrent loop?

推荐答案

如果Fortran过程(函数或子例程)在其定义中具有pure前缀,那么就Fortran使用它而言,它是一个纯过程.然后可以在纯度受限的地方使用.带有前缀elemental而没有前缀impure的过程也是纯的.

If a Fortran procedure (function or subroutine) has the pure prefix in its definition then it is a pure procedure in the sense that Fortran uses it. It can then be used in places where there is a restriction of purity. A procedure with prefix elemental and without the prefix impure is also pure.

要允许将其指定为纯格式,该过程要遵循许多约束条件,但是当给出pure时,编译器必须诊断出是否违反了这些约束条件.

To be allowed to be specified as pure, the procedure is subject to a number of constraints, but it is necessary for the compiler to diagnose any violation of these constraints when pure is given.

没有任何约束可以禁止引用来自另一个模块(或其他作用域)的命名常量.

There is no constraint that a named constant from another module (or other scope) may not be referenced.

作为Fortran中纯度的动力,该标准(F2008,注释12.49)提供:

As motivation for purity in Fortran, the standard (F2008, Note 12.49) offers:

引用已命名的常量并不是对过程外部可见数据的修改.

Referencing a named constant is not modification of data visible outside the procedure.

这篇关于Fortran PURE函数可以使用全局参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:26