Taking a procedure such as
function c(a,b)
integer,parameter :: dp=kind(2.0e0)
real(kind=dp),intent(in) :: a,b
real(kind=dp) :: c
c=a+b
end function
Is there a way to call the same function in the same program with different kinds? For example:
program help
integer,parameter :: sp=kind(2.0d0),dp=kind(2.0e0)
print *, c(2.0_dp,3.0_dp)
print *, c(2.0_sp,3.0_sp)
end program
I know that I can write again the function c using sp parameters and give an interface that hide the two in one, but I'm looking for a solution that don't need to create another function... may be just modify the existing one?
No, there is no way to write a function that accepts arguments of the different kinds of real (or any of the other intrinsics). As you already know, the standard way to write code which is kind-indifferent is to write implementations for each of the kinds you are concerned with and to wrap them in an interface.
You could, if you prefer something more kludgy, write a routine for low-precision kinds which wraps a call to the matching routine for high-precision kinds and incorporates some kind adjustment. Personally I prefer the interface route to this.
Finally, you may well find that your compiler allows you to get away with passing arguments of the wrong kind to a routine, performing some automatic kind adjustment behind the scenes. This is non-standard and likely to be non-portable.
Related
I am learning about fortran C++ interoperability. In this case I was trying to write a 'wrapper' function (f_mult_wrapper) to interface between my 'pure' fortran function (f_mult) and C++. The function is defined in my C code as
double f_mult_by_wrapper(double i, double j);
and called like
double u=f_mult_by_wrapper(w,r);
I know I must specify that the input arguments in f_mult_wrapper are being passed by value from C, and that fortran usually passes by reference. But the compiler gives me an error when I try to specify that the result is being passed by value: A dummy argument name is required in this context. The code works together as written, but I don't exactly understand why.
module type_example
use :: iso_c_binding
function f_mult(i,j) result(k)
! use fortran intrinsic types
real:: i,j,k
k = i*j;
end function
function f_mult_wrapper(aw,bw) result(cw) bind(c,name="f_mult_by_wrapper");
real(c_double), VALUE :: aw ! use c binding types. passed by value
real(c_double), VALUE :: bw
real(c_double) :: cw
real :: a,b,c
a = aw
b = bw
c = cw
c = f_mult(a,b)
cw = c
end function
end module
Function results are simply not function arguments/parameters. They are passed differently and the exact mechanism depends on the ABI (calling conventions) and their type.
In some ABIs, results are passed on the stack. In other ABIs, they are passed using registers. That concerns simple types that can actually fit into registers. More complex objects may be passed using pointers (on the stack or in registers).
The by value/by reference distinction distinguishes, whether the value of the argument is passed on the stack/in the register directly, or indirectly using a pointer. It does not concern function return values.
There are simpler functions that can be C-interoperable and other Fortran functions that cannot be interoperable, e.g. functions returning arrays. Such Fortran-specific functions are implemented in a compiler-specific way. Often, a hidden argument is being passed. Such a hidden argument may contain a pointer and may be passed using a register or using the stack. The details are again dependent on the specific ABI.
For the calling conventions to the most common x86 architecture, see https://en.wikipedia.org/wiki/X86_calling_conventions There are several different variations for 32 bit and for 64 bit.
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
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.
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?
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.
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.
As motivation for purity in Fortran, the standard (F2008, Note 12.49) offers:
The above constraints are designed to guarantee that a pure procedure is free from side effects (modifications of data visible outside the procedure)
Referencing a named constant is not modification of data visible outside the procedure.
From this documentation it should be okay to use a global variable as long as it is a parameter (so the value does not change).
The execution_part and internal_subprogram_part of a pure procedure
cannot refer to a dummy argument with an INTENT(IN), a global variable
(or any object that is storage associated with one), or any subobject
thereof, in contexts that may cause its value to change: that is, in
contexts that produce side effects.
I am mostly doing scientific programming in Python and do not have a whole lot of Fortran (90/95) experience. For one of my projects I want to define a derived type and overload a bunch of operators for that type. Critically, I'd like one of the variables of the derived type to an array of variable length; at least, I need two different lengths in different parts of the code. How can I best achieve this efficiently and avoiding code duplication?
My first approach was to use an allocatable array but that involved several allocate statements throughout the code including the overloaded operators. It also led to difficulties when using the code in an MPI application.
My current approach is two define a type of the same name in two separate modules and use one or the other in different parts of the code. The overloaded operators can be shared using a header file (mytype_operators.h in the example below).
module mod1
type mytype
real :: x1
real,dimension(1) :: x2
end type mytype
#include "mytype_operators.h"
end module mod1
module mod2
type mytype
real :: x1
real,dimension(10) :: x2
end type mytype
#include "mytype_operators.h"
end module mod2
Unfortunately, there is one module in the code with subroutines that I would like to use for both types. Currently I have two copies of that code; one with "use mod1", the other with "use mod2". Can I improve this and avoid the code duplication?
Your case is very suitable for using a Fortran feature introduced in the 2003 standard (and adopted much later by compilers) named parameterized derived types. First of all, you should check the compliance status of your compiler to know if it's fully supported.
This feature allows you to pass custom parameters when declaring or constructing a derived-type, so internal functionality will be adjusted accordingly. They are good for having different behaviour alternatives grouped in a single type name, possibly with considerable coding or storage differences. There are 2 types of parameters:
kind parameters behave much like the kind specifier of intrinsic types. Kind parameters of all variables must be known at compile time and are treated practically as constant values. The convenience is that you could change it easily (in code time) by altering just a value in the declaration or construction. This is commonly used for specializing the kind of components of intrinsic type.
len parameters behave much like the len specifier of intrinsic character type. You can define len parameters at compile time or runtime, and a len parameter of a variable cannot change unless you declared it allocatable. Moreover, you can have arguments with assumed len-parameters in procedures, and avoid code verbosity. This is commonly used as a "length" or "dimension" parameter for a derived type, because you can use them in the declaration of array bounds and character length.
In general, type parameters are used to mimic the functionality of intrinsic types in derived types, but you could also get "creative" and use it for other things, like the dimension-space of a transformation-matrix type; for a custom "union type" (like an enumeration); as the nature of a physical quantity in a "units of measurement" data-type (a real value annotated with "mass" unity is not directly compatible with a "temperature" one, but they can be handled pretty much the same way in the code); the "arity" of a tuple type...
module mod1
type :: mytype(n)
integer, len :: n
real :: x1
real, dimension(n) :: x2
end type mytype
contains
! your operations here...
end module mod1
And use it like this:
program test_pdt
use mod1
implicit none
type(mytype(10)) :: mt10
type(mytype(1)) :: mt1
integer :: i
mt10%x1 = 40.0
mt10%x2 = [(0.5 * i, i = 1, 10)]
mt1 = mytype(1)(20.0, [30.0])
call sub(mt10)
call sub1(mt1)
contains
subroutine sub(m)
! accepts values with any "n" parameter
type(mytype(*)) :: m
! you can also use them in declarations
integer, dimension(m%n + 1) :: y
type(mytype(m%n)) :: w
print *, m%n, w%n, size(y)
end
subroutine sub1(m)
type(mytype(1)) :: m ! only accepts values with n=1
print *, m%x1, m%x2, m%n
end
end
Warning:
This is feature, despite of having been announced many years ago, was just recently added to most compilers, and you should be aware that there are still some bugs in implementation. You should probably be fine with regular use, but I often face false syntax errors in some corner cases, and even ICE sometimes.
I have two derived types (child1 and child2) that both extend from the same abstract type (type, abstract :: parent). The abstract type has a deferred bound procedure.
I want to call a subroutine that performs some stuff (performance critical) depending on the type of the child handed over as input. I can think of two options:
The subroutine takes the class(parent), intent(inout) :: type_in as input. Implementations for the children are then done within a select type (type_in) construct.
I write two subroutines, one with type(child1), intent(inout) :: type_in and one with type(child2), intent(inout) :: type_in and provide an explicit interface to overload the routine name.
The first option allows for implementations where the extension of the parent is not known at compile time, but that is not necessary in my case. It also saves some lines of code because only a part of it is different for the children.
My question is: Is there additional overhead in option one because I implemented the input as polymorphic data when the type is known at compile time?
Yes, there is additional cost of a so call virtual call. A virtual method table (as it is called in other languages) is used and searched for the right procedure to call. The cost is likely to be similar to that of a virtual function call in C++, see https://stackoverflow.com/a/453001/721644
The compiler is sometimes able to find out which procedure is called by the binding even at compile time. For example, when the actual passed object is non-polymorphic. GCC has two flags -fdevirtualize and -fdevirtualize-speculatively (enabled with -O2, -O3, -Os) which convert virtual calls to direct calls. They are likely applicable to Fortran too.
I am converting fortran code to C++ and wanted to find a right option for function-pointer.
The fortran code is: for two different cases, it passes two different kinds of function-pointers to another function. These function pointers have different interfaces. In C++, I need to specify interface of function-pointer and hence it is not straightforward. Can someone suggest, if C++ functor or something else, that would be useful? I wish I could use something like 'void (function) pointer' and then 'cast', but I really don't know. Thanks in advance.
EDIT: minimal example in fortran
Fortran
if(option1) then
call myfunc( abc_function_pointer,otherarguments)
else
call myfunc( xyz_function_pointer, otherarguments)
endif
where, these functions are (in C++)
void (*abc_function_pointer)(int, float) //in c++
void (*xyz_function_pointer)(int, int, int) //in c++
Generally speaking, this is a bad idea. Consider - what is myfunc going to do with this function pointer? What happens if you pass it abc_function_pointer, but it tries to call it with three ints? Or vice versa?
Without knowing what you're using this for, it's hard to suggest what you should do. Typically you would want to factor out the common interface between abc_function_pointer and xyz_function_pointer, so myfunc always calls a function with the same type and interface. You can insert a shim function that converts between the common interface and that of abc_function_pointer or xyz_function_pointer.