ASSOCIATE chains in Fortran?

607 Views Asked by At

The ASSOCIATE feature is in principle quite useful, as it allows assigning values to names without incurring the syntactical overhead of explicitly defining local variables. However, its utility is limited because the values are bound only after the ASSOCIATE statement. This quickly leads to the need for nested associate statements, e.g.

PROGRAM toyexample
  IMPLICIT NONE
  ASSOCIATE(a => 2)
    ASSOCIATE(b => [a, 2*a, 3*a])
      PRINT *, a
      PRINT *, b
    END ASSOCIATE
  END ASSOCIATE
END PROGRAM toyexample

In Lisp terms, this would be the behavior of let, while I seek to emulate the behavior of let*, which would allow me to write

PROGRAM toyexample
  IMPLICIT NONE
  ASSOCIATE(a => 2, b => [a, 2*a, 3*a])
    PRINT *, a
    PRINT *, b
  END ASSOCIATE
END PROGRAM toyexample

Is there any feature in Fortran that allows me to do this?

1

There are 1 best solutions below

1
Serge3leo On
program toyexample1
    implicit none

    integer, parameter :: a = 11
    integer, parameter :: b = 22
    integer, parameter :: c = 33

    associate(a => b, b => c, c => a)
        print *, a, b, c ! Intel Fortran print: 22 33 22, other 22 33 11
    end associate
    block; integer, parameter :: a = b, b = c, c = a ! NAG Fortran rejected
        print *, a, b, c ! All compilers print: 22 33 22
    end block
    block; integer, parameter :: a = 2, b(*) = ([a, 2*a, 3*a]) ! PGfortran crash
        print *, a, b(:) ! All compilers print 2 2 4 6
    end block
end program toyexample1