FORTRAN implicit cast when argument association happens in procedures - casting

I am using fortran for a while, but I didn't check the implicit cast issue when using subroutines in fortran.
For example
subroutine printa(a)
double precision :: a
...
endsubroutine printa
When I called the subroutine
call printa(1)
I saw error #6633: The type of the actual argument differs from the type of the dummy argument. [1]
I know it is because I use an integer instead of a double precision as an input parameter. But I just realized that there is no implicit cast when using subroutines.
If I want a subroutine which handles integer and double precision data, it seems I have to define 2 subroutines for doing these things. Is there a way to make the implicit cast happen (just like the function calling in c)? Or there is another way to make it?
Thanks.

It is fundamental in Fortran that reals (including different precisions) and integers are different and that you need different subroutines to handle them. If you want the convenience of having a single call, similar to Fortran intrinsics such as sin which are implicitly several different functions, you can write the several different procedures and then create a generic interface to select between them. Fortran will then select the correct actual procedure based on the actual arguments, to match the dummy arguments. Here is an example that does it by rank of the array argument: how to write wrapper for 'allocate'. It can also be done, as you wish, by type of the argument.

You can overload a subroutine name so that when the "wrong" type of argument is supplied it is converted to right type and used to call the subroutine, as shown below.
module foo
implicit none
interface printa
module procedure print_int,print_real
end interface printa
contains
!
subroutine print_real(x)
real, intent(in) :: x
print*,"number is ",x
end subroutine print_real
!
subroutine print_int(i)
integer, intent(in) :: i
call print_real(real(i))
end subroutine print_int
!
end module foo
program main
use foo, only: printa
implicit none
call printa(1)
call printa(1.0)
end program main
Output:
number is 1.
number is 1.

Related

How do variable declarations within types work in Fortran?

I'm trying to learn Fortran, and I've found that there aren't very many tutorials out there (probably due to it being an old language). The ones I have found are vague and undescriptive, and as I've gone into more complex things it has become harder and harder to guess what said tutorials are saying.My current issue is with creating types. The tutorial contains examples such as:
module m_shapes
implicit none
private
public t_square
type :: t_square
real :: side
contains
procedure :: area ! procedure declaration
end type
contains
! Procedure definition
real function area(self) result(res)
class(t_square), intent(in) :: self
res = self%side**2
end function
end module m_shapes
This compiles fine, so I know it works.
When I try to do something similar like this:
program type_test
implicit none
type :: thingy(a)
real :: a
end type
end program
It doesn't compile with errors like "The component at (1) that appears in the type parameter list at (2) has neither the KIND nor LEN attribute"
The tutorial I found does not explain types well enough, and I've tried things like real,kind :: a = kind(0.0), but to no avail. Does anybody know what's wrong?
Thanks in advance.
You did not explain, what you actually want to do. Or your words are not nearly clear enough. We can tell you why your attempt produces the error, but I have no idea what you actually want to do.
Perhaps you just wanted
program type_test
implicit none
type :: thingy
real :: a
end type
end program
without the (a)? That declares a simple type with one component. But hard to guess if this is what you wanted and what you tried with the (a).
It does not declare any variable with that type. That is done using
type(thingy) :: var
The syntax
type :: thingy(a)
real :: a
end type
attempts to declare a parametrized derived type. These types can depend on a kind or length parameter. These parameters must be integers. If it is a kind parameter, it allows to declare variables of the type with varying values of these parameters. Then the kind of some components of the type (you know what kind is, right? Fortran 90 kind parameter ) get their kind according to the value of the parameter. If it is a length parameter, it allows the length of some array or string components of the derived type to be parametrized - set during the variable declaration.
These parameters that appear in the parenthesis must be integer components and must have the kind or len attribute.
For example
type :: param_type(k,l)
integer, kind :: k
integer, len :: l
real(kind=k), dimension(l) :: array
end type param_type
type(param_type(kind(1.), 10)) :: o_sp_10
type(param_type(kind(1.d0), 20)) :: o_dp_20
The values of the parameters are set during the declaration of those o_sp_10 and o_dp_20 objects. I do not want to go into more details.

Is it possible for an overloaded procedure to have a different interface from that of its parent class?

Is it possible to extend a class and overload one of its procedure with one with a different interface?
I would like to create multiple type (say tensor1, tensor2, ...) extending a base class tensor , all implementing a method sub whose arguments depend on the subclass.
Consider the following code:
module tensor_class
implicit none
private
public :: tensor_Type
type, abstract :: tensor_Type
Contains
procedure,pass(self) :: sub
end type
Contains
subroutine sub(self,other)
class(tensor_Type),intent(inout) :: self
integer :: other
write(*,*) 'sub is not implemented in the main class'
end subroutine
end module tensor_class
module tensor1_mod
use tensor_class
type, extends(tensor_type) :: tensor1
real,dimension(2) :: val
Contains
procedure, pass(self) :: sub
end type tensor1
Contains
subroutine sub(self,other)
class(tensor1),intent(inout) :: self
real,dimension(2),intent(in) :: other
self%val = self%val + 2.0 * other
end subroutine
end module
module tensor
use tensor1_mod
end module
program testTensor
use tensor
implicit none
class(tensor_type),allocatable :: t
type(tensor1) :: t1
real,dimension(2) :: v1 = [1.0,-2.3]
integer :: i
t1 = tensor1(v1)
t = tensor1(v1)
call t1%sub(i)
call t%sub(i)
end program
Neither Intel Fortran (19.1.1.216 20200306) nor gfortran (9.3.0) will compile it. The Intel compiler prints the following error message
tensorMin.F90(25): error #8383: The dummy arguments of an overriding and overridden binding that correspond by position must have the same characteristics, except for the type of the passed object dummy arguments. [SUB]
and gfortran
>tensorMin.F90:25:15:
25 | procedure, pass(self) :: sub
| 1
Error: Argument mismatch for the overriding procedure 'sub' at (1): Type mismatch in argument 'other' (REAL(4)/INTEGER(4))
I cannot declare sub as deferred in tensor_class, if I want to be able to create multiple subclasses and have sub take different type of arguments in each class (say real, dimension(2) in tensor1, real, dimension(2,2) in tensor2 etc).
Upon reading of the Fortran 2008 standard section 4.5.7.3, it seems that the name and number of arguments in sub need to match, but the standard does not seem to say anything about the type of the arguments.
Am I missing something? Is there a way other than creating a class containing all possible arguments of sub?
The Fortran standard does require the argument types to match.
Except for the passed-object dummy arguments the standard says that the dummy arguments which correspond shall have the same characteristics. (This the Intel Fortran error message states.) The type of a dummy argument is one characteristic (of many) of that argument.
You can look in to polymorphic arguments (as in your comment) or at generic bindings.

Does the finalization routine need to be elemental in order to be called on the elements of allocatable array that goes out of scope?

If I have an allocatable array of a finalizable derived type, will the finalizer be called on every individual element when the array goes out of scope?
Here is a small code example that illustrates the question:
module LeakyTypeModule
implicit none
private
type, public :: LeakyType
real, pointer :: dontLeakMe(:) => null()
contains
procedure :: New
final :: Finalizer
end type
contains
subroutine New(self, n)
class(LeakyType), intent(out) :: self
integer , intent(in) :: n
allocate(self%dontLeakMe(n))
self%dontLeakMe = 42.0
end subroutine
subroutine Finalizer(self)
type(LeakyType), intent(inout) :: self
if (associated(self%dontLeakMe)) deallocate(self%dontLeakMe)
end subroutine
end module
program leak
use LeakyTypeModule
implicit none
type(LeakyType), allocatable :: arr(:)
allocate(arr(1))
call arr(1)%New(1000)
deallocate(arr)
end program
Note that this program leaks the dontLeakMe array allocated in the New() method of LeakyType. At first this was a bit surprising for me but, then I discovered that the problem can be fixed by declaring the finalizer elemental. Both gfortran and ifort behave in the same way, so I assume this behaviour is following the Fortran 2003 standard.
Can anyone confirm this? To be honest I have a hard time time understanding what the standard says on this particular point.
Right now I also can't see much use in not declaring all my finalizers elemental. Does this have any application I'm overlooking?
The rules for determining whether a final procedure is invoked, and which final procedure is invoked, are the same as for resolution of generic procedures in terms of rank matching requirements.
Noting that the question is tagged Fortran 2003...
Elemental procedures in Fortran 2003 and prior have to be PURE. If your finalizer needs to do something that is incompatible with the pure attribute (which is reasonably common) then the finalizer cannot be elemental, and you need to write the rank specific variants.
Fortran 2008 introduces the concept of IMPURE ELEMENTAL, which is quite handy for writing finalizers.

Why do the names of overriding arguments have to match those of the abstract interface?

Why do the names of arguments in overriding procedures need to match those of the abstract interface?
I understand that clearly the TYPE, INTENT, etc of such arguments are required to match the interface, but why should the compiler care what I call my variables?
In the following, I've defined a simple abstract utility class containing a single deferred procedure EVAL that takes a double precision argument.
!------------------------------------- an abstract utility class !
type, abstract :: func_1d
contains
procedure(interface_1d),deferred :: eval
end type func_1d
!-------------------------------------------- interface for eval !
abstract interface
function interface_1d(this,data) result(rval)
import :: func_1d
class(func_1d), intent(inout) :: this
real*8 , intent(in) :: data
real*8 :: rval
end function interface_1d
end interface
Defining an overriding class and an implementation for EVAL:
type, extends(func_1d) :: foo
contains
procedure, pass :: eval => eval_foo
end type foo
function eval_foo(this,another_variable_name) result(rval)
implicit none
class(foo), intent(inout) :: this
real*8, intent(in) :: another_variable_name
real*8 :: rval
!! etc
end function eval_foo
I get the following error from gfortran:
Error: Dummy argument 'another_variable_name' of 'eval' at (1) should be named 'data'
as to match the corresponding argument of the overridden procedure
If I instead substitute DATA for ANOTHER_VARIABLE_NAME everything compiles and runs as expected.
But this seems silly to me. I want to be able to inherit from FUNC_1D multiple times, and under various circumstances and being forced to call my variables DATA every time seems ridiculous.
I don't understand why the compiler should be interested in more than the TYPE and INTENT of the arguments?
Elaborating on High Performance Mark's comment
I don't know but I suspect that it may be down to Fortran's argument keyword capabilities, which mean that you can call your function like this fun_1d(data=the_data,this=that), that is you can name the arguments in the call rather than rely on position matching.
consider the following
type, extends(func_1d) :: foo
contains
procedure, pass :: eval => eval_foo
end type foo
type, extends(func_1d) :: bar
contains
procedure, pass :: eval => eval_bar
end type bar
with appropriate procedure definitions with interfaces
real*8 function eval_foo(this,foo_var)
class(foo), intent(inout) :: this
real*8, intent(in) :: foo_var
end function
real*8 function eval_bar(this,bar_var)
class(bar), intent(inout) :: this
real*8, intent(in) :: bar_var
end function
then later
class(func_1d), allocatable :: baz
allocate (foo_or_bar :: baz) ! For one of the types foo, bar
which, if any, makes sense with an argument keyword?
print*, baz%eval(data=s)
print*, baz%eval(foo_var=s)
print*, baz%eval(bar_var=s)
[There are cases where this would be much more pronounced, especially with optional dummy arguments.]
The standard requires that you keep the same dummy argument names (very likely to avoid the issue above). See 12.4.1 ISO/IEC 1539-1:2010:
12.4.1 Interface and abstract interface
The interface of a procedure determines the forms of reference through which it may be invoked. The procedure’s
interface consists of its name, binding label, generic identifiers, characteristics, and the names of its dummy
arguments. The characteristics and binding label of a procedure are fixed, but the remainder of the interface may
differ in differing contexts, except that for a separate module procedure body (12.6.2.5), the dummy argument
names and whether it is recursive shall be the same as in its corresponding separate interface body (12.4.3.2).
This states that separate procedures using the same interface shall have the same dummy argument names as the interface. This is further strengthened by 4.5.7.3:
The overriding and overridden type-bound procedures shall satisfy the following conditions.
- [...]
- Dummy arguments that correspond by position shall have the same names and characteristics, except for the type of the passed-object dummy arguments.

Is it possible to disable named argument calling ?

I have two routines whose difference is only in the order of arguments, but I would like to use them through an interface, so that the proper one is invoked according to the order of the arguments when invoked. The compiler complains that it cannot distinguish them, and my guess is because if I use the syntax for named arguments at call, it won't know which one to call. One workaround would be to use different names for the arguments, but I was wondering if there's a way to disable named argument call style.
Example, this is the situation I am trying to handle
module Foo
interface Bar
module procedure Bar1
module procedure Bar2
end interface
contains
subroutine Bar1(i,r)
integer, intent(in) :: i
real, intent(in) :: r
print *, "bar1"
end subroutine
subroutine Bar2(r,i)
real, intent(in) :: r
integer, intent(in) :: i
print *, "bar2"
end subroutine
end module
program fuux
use Foo
integer :: i
real :: r
r = 5.0
i = 3
call Bar(i,r) ! note that if I call Bar(i=i, r=r) the compiler cannot disambiguate
! so it will complain at the interface statement
end program
I do not know of any way to do what you suggest, or rather to do what I think you are suggesting in the phrase 'disable named argument call style'. If this answer infuriates, disappoints or displeases in any way, post some code and we (SO I mean, I have not too many airs and graces and rarely use the royal 'we') might be able to suggest a cunning trick which will please you.
EDIT
No direct way to do what you want to do springs to mind. The first workround that occurs to me is to define a subroutine called bar which takes the series of arguments in a canonical order and simply calls bar1, bar2 (and any other baby bars you care to define) with the arguments in the appropriate order.