Generic interface to convert user type to array - fortran

I have a simple user-defined type
use, intrinsic :: iso_fortran_env
implicit none
type :: vector
real(real64) :: data(3)
end type
that has various interfaces defined as well as the assignment operator to and from arrays.
What I need is an abstract interface
interface assignment(=)
procedure v_to_a_assign, a_to_v_assign
end interface
which means I can do things like
type(vector) :: v
real(real64) :: a(3)
a = v
But what I want to do is an array-constructor such as
type(vector) :: v
real(real64) :: q(4)
q = [1d0, v]
! error #8209: The assignment operation or the binary expression operation is
! invalid for the data types of the two operands. [v]
which I could do if v was an array of real(real64). My question here is what binary operation do I need to define to make the above work?
The above is just one example of an implicit conversion of a user type to an array. I want to define the correct operator such that my user type is automaticall converted to an array when needed, like in function arguments, and/or other constructs.
Solution
define an interface for the conversion using the keyword real.
interface real
procedure v_to_array
end interface
contains
function v_to_array(v) result(a)
type(vector), intent(in) :: v
real(real64), dimension(3) :: a
a = v%data
end function
and use it as
q = [1d0, real(v)]
References Array Constructors

The language does not support the implicit conversion you are after.
Reference the array component, either directly using the component within the array constructor:
q = [1.0_real64, v%data]
or write an appropriate accessor function/unary operator.
q = [1.0_real64, .getdata. v]
The implicit conversion you seek would be problematic given the way generic resolution is defined by the language.
As a matter of style, explicit conversions are often preferred - for example user a structure constructor as the expression instead of the user defined assignment when assigning to an object of type vector, use an accessor function or unary operator when assigning to an array of real. Beyond clarity, user defined assignment does not invoke automatic (re)allocation of the variable on the left hand side of an assignment.
(Fortran does not have an assignment operator - it has an assignment statement.)

Related

Overload subscript operator in Fortran

I have some matrix type that can either be real or complex:
type t_mat
logical :: is_real
real :: data_r(:,:)
complex :: data_c(:,:)
end type
and I would like to overload the =-operator as well as the (i,j) operator, so that I could conveniently say:
type(t_mat) :: a
...
a(2,3) = 3
I know in C++ it is possible to overload the subscript operator. Does Fortran allow for something similar?

Parametrized derived types with kind parameter as subroutine argument

Say we have the following code:
module foo
use :: iso_fortran_env
implicit none
type :: bar (p, q)
integer, kind :: p
integer, len :: q
integer(kind = p), dimension(q) :: x
end type bar
contains
subroutine barsub (this)
class(bar(*,*)), intent(in) :: this
write (*,*) this%x
end subroutine barsub
end module foo
This code does not compile with either gfortran 8 or pgfort 18.4. The pgi compiler says
Illegal selector - KIND value must be non-negative
Assumed type parameter (*) cannot be used with non-length type parameter p
whereas gfortran yields
The KIND parameter 'p' at (1) cannot either be ASSUMED or DEFERRED
If I change above code to
subroutine barsub (this)
class(bar(INT32,*)), intent(in) :: this
write (*,*) this%x
end subroutine barsub
it compiles fine with both compilers.
Is it possible to write a subroutine where the kind parameter does not need to be specified explicitly? In the example above, the code would be the same for INT32, INT64, ... and I don't want to copy paste it for every imaginable value of the kind parameter. It works fine for the len parameter. Why can't I do the same with the kind parameter?
Is it possible to write a subroutine where the kind parameter does not need to be specified explicitly?
No, kind type parameters need to be given by a constant expression or defaulted, see, e.g., the Fortran 2008 standard, definition 1.3.147.12.3.
Why can't I do the same with the kind parameter?
The fact that len and kind type parameters have different uses and requirements is the point of having two types of type parameters, if their characteristics were the same we wouldn't need two of them.
Note that procedures require of the kind parameters of their dummy arguments of parameterized derived types just same they require of the kinds of their dummy arguments of intrinsic types: to have their values defined at compilation time.

Automatic LHS reallocation with overloaded assignment

I have a code, which segfaults with all compilers I have at hand, when doing an assignment to an unallocted allocatable on the LHS with a structure constructor on the RHS. The structure (derived type) itself has an overloaded assignment. I thought, that automatic reallocation of the LHS should occur before the assignment routine is called, but it does not seem to be the case.
Below the code, demonstrating the issue. Uncommenting the allocate statement makes everything working, but I do not understand, why the explicit allocation is necessary in this case. Funny enough, if I remove the overloaded assignment, things work as well.
Any hints?
module dummy
implicit none
type :: DummyType
integer :: ii
contains
procedure :: assignDummyType
generic :: assignment(=) => assignDummyType
end type DummyType
interface DummyType
module procedure DummyType_init
end interface DummyType
contains
function DummyType_init(initValue) result(this)
integer, intent(in) :: initValue
type(DummyType) :: this
this%ii = initValue
end function DummyType_init
subroutine assignDummyType(this, other)
class(DummyType), intent(out) :: this
type(DummyType), intent(in) :: other
this%ii = other%ii + 1
end subroutine assignDummyType
end module dummy
program test_dummy
use dummy
implicit none
type(DummyType), allocatable :: aa
!allocate(aa) ! Should be covered via automatic reallocation...
aa = DummyType(42)
end program test_dummy
There is a recent discussion on comp.lang.fortran dealing with this topic.
An assignment statement is either an intrinsic assignment or a defined assignment. Intrinsic assignment permits [re]allocation of the left hand side, defined assignment does not.
When you provide a procedure for the assignment generic identifier, your assignment is defined assignment. The characteristics of the argument that corresponds to the left hand side then require that the left hand side be allocated.

Nested derived type with overloaded assignment

I have a derived type (wrapper) containing an other derived type (over). For the latter the assignment operator have been overloaded. As the assignment of derived types happens per default componentwise, I'd expect that assigning two instances of wrapper would invoke the overloaded assignment for over at some point. However, using the program below, it does not seem to be the case. The overloaded assignment is only invoked if I also overload the assignment for wrapper containing an explicit assignment between instances of over (by uncommenting the commented code lines). Why? I find it somewhat counter intuitive. Is there any way to avoid the overloading in the wrapping type?
module test_module
implicit none
type :: over
integer :: ii = 0
end type over
type :: wrapper
type(over) :: myover
end type wrapper
interface assignment(=)
module procedure over_assign
!module procedure wrapper_assign
end interface assignment(=)
contains
subroutine over_assign(other, self)
type(over), intent(out) :: other
type(over), intent(in) :: self
print *, "Assignment of over called"
other%ii = -1
end subroutine over_assign
!subroutine wrapper_assign(other, self)
! type(wrapper), intent(out) :: other
! type(wrapper), intent(in) :: self
!
! other%myover = self%myover
!
!end subroutine wrapper_assign
end module test_module
program test
use test_module
implicit none
type(wrapper) :: w1, w2
print *, "Assigning wrapper instances:"
w2 = w1
end program test
This [unfortunate] situation is a consequence of the rules of the language (F90+) for intrinsic assignment of derived types. The details are spelled out in F2008 7.2.1p13. As a summary, intrinsic assignment of derived types (the assignment that happens with the wrapper_assign specific commented out) does not invoke non-type bound defined assignment for any components that are of derived type. In F90/F95, if you want defined assignment at some lower level of the component hierarchy then you need to have defined assignment for all the parent components up to the base object.
F2003 added type bound defined assignment to the language and this is invoked by intrinsic assignment of derived types. Use that instead of the stand-alone generic form of specifying defined assignment. (This also avoids a potential problem with the type name being accessible but the defined assignment procedure not being accessible.)
Just to complete the thread: the concrete realisation of IanH's suggestion (please upvote his original answer rather than this one) which worked for me was the following one:
module test_module
implicit none
type :: over
integer :: ii = 0
contains
procedure :: over_assign
generic :: assignment(=) => over_assign
end type over
type :: wrapper
type(over) :: myover
end type wrapper
contains
subroutine over_assign(other, self)
class(over), intent(out) :: other
class(over), intent(in) :: self
print *, "Assignment of over called"
other%ii = -1
end subroutine over_assign
end module test_module
program test
use test_module
implicit none
type(wrapper) :: w1, w2
print *, "Assigning wrapper instances:"
w2 = w1
end program test

No lifting of scalar arguments to arrays in Fortran

Why is it that Fortran will promote a scalar expression to an array, in an expression, but not as an argument to a procedure? In particular, why did the standards body make this design decision? Is it solely because of ambiguity, should the procedure be overloaded? Could an error message in that situation be an alternative approach?
For example, In the code below, the last statement, x = foo(7), produces the GFortran error: Error: Rank mismatch in argument 'a' at (1) (1 and 0).
module m
public :: foo
contains
function foo(a) result(b)
integer, dimension(:) :: a
integer, dimension(size(a)) :: b
b = a+1
end function foo
end module m
program p
use m
integer, dimension(4) :: x
integer, parameter, dimension(4) :: y = (/1,2,3,4/)
x = 7
x = foo(x)
x = foo(y)
x = foo(x + 7)
x = foo(7)
end program p
This question should have asked about why an array assignment will promote a scalar value source to an array target; unlike an array function. I expect that's simply a convenient special case though. Any comments gratefully received in the begging caps below.
If you want the function to handle scaler and array arguments, declare it as "elemental" and with scaler dummy arguments. Then it will be able to handle both scaler and array actual arguments, including scaler expressions. Will that meet your need?
The change:
elemental function foo(a) result(b)
integer, intent (in) :: a
integer :: b
b = a+1
end function foo
Perhaps they provided a way to do what you want, and one way was enough?
Procedure calling in Fortran with explicit interfaces (which you get automatically when using module procedures) requires a TKR (type, kind, rank) match. As an array is a different type than a scalar, not to mention the rank mismatch, this is not allowed.
Is it because of ambiguity should the procedure be overloaded?
That would be a problem, yes.
Could an error message in that situation be an alternative approach?
Could pink unicorns exist? Maybe, but to the best of my knowledge they don't. IOW, the Fortran standard currently requires TKR matching, and thus a standard conforming compiler must enforce this requirement. If you want to change that, I recommend making a proposal to the standards committee.
I would think the answer to this is pretty clear. Let's slightly modify your example:
module m
public :: foo
contains
function foo(a) result(b)
integer, dimension(:) :: a
integer, dimension(size(a)) :: b
b = a+1
a(2) = -777 ! new line; modify one element
end function foo
end module m
program p
use m
integer :: x
integer, dimension(4) :: y
x = 7
y = foo(x) ! pass a scalar
end program p
what is x supposed to be after the call to foo?
Now, sure, you could have the semantics of argument passing change depending on whether or not it's an intent(in) variable, but that is not something which is going to clarify things for programmers.
If the function call is supposed to 'distribute' somehow over array elements, then as MSB points out, elemental is the way to go. Otherwise, one just makes sure one's arguments match one's parameters.