I had a question about the correct way of programming user-defined operators in Fortran. To be more specific, I will provide the example of my problem. I am working on creating a user-defined data type for spherical particles called 'Particle'. I want to define an operator that takes an existing array of Particle objects and adds a new Particle object to it. I was wondering how I would go about defining user defined operators to do such an action.
Currently I have, within the type definition for Particle, the following lines:
procedure, public:: addNewParticleTo
generic:: operator(.spawn.) => addNewParticleTo
Following which, I have a subroutine that is defined as follows:
subroutine addNewParticleTo(a_LHS, a_RHS)
implicit none
class(Particle), dimension(:), allocatable, intent(in):: a_LHS
class(Particle), dimension(:), allocatable, intent(inout):: a_RHS
<rest of the code>
end subroutine addNewParticleTo
I intend for the operator to be invoked as:
particle .spawn. particleArray
I was wondering if this is the correct way to go about doing this. Any suggestions or advise on this will be very helpful.
To expand on the comments, you will need to have the operator code as a function. Further, each input would need to be intent(in). This would indeed allow something like array = particle .spawn. array.
However, another change is required to your subroutine: one of your arguments should be a scalar. [The first, unless you play with the pass attribute.]
function addNewParticleTo(A, B) result(C)
class(particle), intent(in) :: A
class(particle), allocatable, intent(in) :: B(:)
class(particle), allocatable :: C(:)
! ... code to do the appending
end function
Finally, my advice is that having this as a type-bound operator is making things quite complicated, with the polymorphism and so on. Also, array = particle .spawn. array seems very unintuitive.
Instead, just a plain subroutine so that call add_to_particle_array(all_particles, new_particle) works seems cleaner. This is closer to your original code, but doesn't answer your question about operators, alas.
Related
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.
I would like to know whether it is possible in modern Fortran to assign an allocatable array using itself, or part of it, to do it. Here it is a simple example:
module modu
implicit none
type :: t
integer :: i
end type
contains
subroutine assign(a,b)
type(t), allocatable, intent(out) :: a(:)
type(t), intent(in) :: b
allocate(a(1))
a(1) = b
end subroutine
end module
!----------------------
program test
use modu
implicit none
type(t), allocatable :: a(:)
allocate(a(1))
a(1)%i = 2
call assign(a, a(1))
print*, a(1)%i
end program
This code gives the corect answer with ifort 18 and returns "Segmentation fault" with gfortran 7.4.
NOTE: The original problem was a bit more complex since call assign(a, a(1)) should be replaced by call assign(a, a(1)+b) having operator + properly overloaded, but the conclusion (respect ifort and gfortran) is the same.
NOTE: In the thread checking for self-assignment in fortran overloaded assignment, #IanH makes a distinction between call assign(a,a) and call assign(a,(a)) but I believe that it does not solve this problem because I have allocatable arguments.
NOTE: In the thread Automatic array allocation upon assignment in Fortran, #francescalus explains automatic allocation on intrinsic assignment but again I believe that it does not apply here.
This call
call assign(a, a(1))
is forbidden by the aliasing rules of Fortran. You are passing the same value in different arguments and neither is pointer or target and you are modifying one of them.
Then, the compiler deallocates a because it is intent(out). That means that the old a(1) no longer exists. But b still points there. Then you allocate a new a somewhere else. Then you try to use b in
a(1) = b
and that is bound to fail because it points to some undefined piece of memory. You are just lucky with Intel Fortran, but your code is illegal. Maybe Intell allocated the new a to the same place where the old a was, but that is pure luck.
It will work if you do
type(t), allocatable, intent(inout) :: a(:)
type(t), value :: b
deallocate(a)
allocate(a(1))
a(1) = b
I am not sure, why it crashes with intent(out) and value. It may be a problem with the compiler, reported as bug 92178.
It is possible to assign to an allocatable array using array elements of that same array. For example, for a allocatable
a = [a(2), a(1)]
is valid and has the expected result. This is the same whether a is an intrinsic type (for intrinsic assignment) or of derived type (for intrinsic or defined assignment). The right-hand side is treated as evaluated fully as an expression before the left-hand side becomes affected.
However, using call assign(a,a(1)) is not the same thing as this assignment.
The point in the answer by IanH you reference is relevant here. Defined assignment would be like call assign(a,(a(1))) rather than call assign(a,a(1)).
This is important because of the aliasing restrictions mentioned in Vladimir F's answer which I won't repeat. Using call assign(a,(a(1))) removes the aliasing because (a(1)) is an expression with value that of the array element rather than the array element itself. This is similar to the value attribute Vladimir F mentions, but without creating a definable entity.
Defined assignment uses the (rhs) construct precisely to avoid this aliasing issue.
Regarding your gfortran results, IanH created a bug report for GCC in response to that other question. It may well be relevant in explaining the surprise you have here.
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.
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.
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.