Re: Pure and internal procedures



On 9-12-2011 4:12, Michael Trover wrote:
Think of it this way. This is an example using a function whose
interface we know and a code snippet.

Example 1:

interface
function f(x)
real, intent(in):: x
end function
end interface

x = 3.0
y = f(x)
z = f(x)

In this example the function invocations for y and z have to be done.
That is the code has to invoke the function twice. The second invocation
of f may not return the same value as the first invocation.

Example 2:

interface
pure function f(x)
real, intent(in):: x
end function
end interface

x = 3.0
y = f(x)
z = f(x)

Here the compiler knows, just from the interface, that it only needs to
invoke the function once and copy the result to both y and z. That's the
power of PURE.


Unless the variable y is host accessible by the pure function, and the function uses its value to calculate the result.

The following program prints

y = 3.0
z = 6.0

program pure_p
implicit none

real :: x, y, z

y = 0.0

x = 3.0
y = pure_f(x)
z = pure_f(x)

write(*, '("y = ", f0.1)') y
write(*, '("z = ", f0.1)') z
contains
pure function pure_f(x)
real, intent(in) :: x
real :: pure_f

pure_f = x + y
end function pure_f
end program pure_p

Erik.
.



Relevant Pages

  • Re: Interface block inside a subroutine.
    ... pure function dY ... end interface ... I don't think I fully understand the difference between a module procedure and a "dummy" procedure. ... pure subroutine rk4_val ...
    (comp.lang.fortran)
  • How can I make this module less repetitive?
    ... I wrote a module that provides a few basic ODE integrators. ... So I end up writing a nearly identical routine three times, and using an interface block to join them together. ... pure subroutine rk4_val ... pure function dY ...
    (comp.lang.fortran)
  • Re: Fortran templates
    ... at compile time, what do you want to sort. ... end type mytype ... end interface operator ... pure function compare_int ...
    (comp.lang.fortran)
  • Re: Are these two different interfaces or not?
    ... Your actual argument is a null pointer. ... actual argument unless the dummy argument is also a pointer (or I think ... abstract interface ... pure function this_is_a_functionresult ...
    (comp.lang.fortran)
  • Assumed-shape arrays -- Need help with a Runge-Kutta integrator
    ... pure function runge_kutta_stepresult ... end interface ... The only problem with this is that the size of the array is hard-coded "r_" at 4. ... But I don't see how you could implement Runge-Kutta with elemental functions, since the derivative function "dr" is not, in general, elemental. ...
    (comp.lang.fortran)