在Fortran中调用针对派生类型数组的类型限定过程

3

假设我有一个派生类型Coordinates和它的类型限定过程swap:

module myTypes
    implicit none
    public :: Coordinates  

    type Coordinates
        real :: x,y
    contains
        procedure :: swap  ! Error here
    end type
contains
    subroutine swap(this)
        class (Coordinates) :: this
        this%x = this%x + this%y
        this%y = -(this%y - this%x)
        this%x = this%x - this%y
    end subroutine
end module

现在,如果我有一个名为point_ACoordinates实例,并且如果我想要调用它的类型绑定过程swap,我只需编写:call point_A%swap。但是,如果我有一个Coordinates实例数组,如下:

type(Coordinates), dimension(:), allocatable :: setOfPoints

那么要对setOfPoints的所有元素调用swap,我想要写成:

call setOfPoints(:)%swap

为了实现这个目标,我修改了swap 过程的代码为:
subroutine swap(these)
        class (Coordinates), dimension(:)  :: these
        integer :: i
        do i = 1, size(this)
            this(i)%x = this(i)%x + this(i)%y
            this(i)%y = -(this(i)%y - this(i)%x)
            this(i)%x = this(i)%x - this(i)%y
        end do
end subroutine

很不幸,gfortran不喜欢我的想法。在我标记的第一段代码中,它会显示:

Error: Passed-object dummy argument of 'swap' must be scalar.

问题:如何一次性调用派生类型的所有实例的类型限定过程?我不想在循环中放置调用,但是我希望像在Fortran中对数组进行操作一样,按照之前编写的方式进行操作。
我了解了关键字,但如果我想使用它,那么我需要让类型限定的过程是“pure”的,而这不是我的情况。我尝试在后面放置一个关键字,但编译器则报错:
Error: Interface must be specified for DEFERRED binding

我为swap创建了一个接口,但是我无法确定应该将其放置在哪里。我尝试了许多位置,但编译器报错说“意外的接口”。 此外,我了解了SELECT TYPE,但我认为它在我的情况下没有帮助。

1个回答

2

您的具体例子完全可以使用ELEMENTAL技术。

module myTypes
    implicit none
    public :: Coordinates  

    type Coordinates
        real :: x,y
    contains
        procedure :: swap  ! Error here
    end type
contains
    elemental subroutine swap(this)
        class (Coordinates), intent(inout) :: this
        this%x = this%x + this%y
        this%y = -(this%y - this%x)
        this%x = this%x - this%y
    end subroutine

end module

 use myTypes

 type(Coordinates) :: arr(10)

 arr = Coordinates(1.,2.)

 call arr%swap

 end

你的子程序是纯净的。如果不可能,考虑使用杂元素


非常感谢!“不纯的元素”对我来说很好用!P.S.:确实,在这里我忽略了一些使子程序变得不纯的代码行。 - Georgy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接