我正在尝试在 Fortran (95) 中创建一个函数,该函数将输入一个字符串 ( test ) 和一个字符 ( class )。该函数将 test 的每个字符与字符 class 进行比较,如果它们属于相同的 class1 则返回一个逻辑值 .true. 否则返回 .false.

函数(以及运行它的程序)定义如下:

!====== WRAPPER MODULE ======!
module that_has_function
implicit none
public

contains

!====== THE ACTUAL FUNCTION ======!
function isa(test   ,class  )
implicit none

logical, allocatable, dimension(:) :: isa
character*(*) :: test
character :: class

integer :: lt
character(len=:), allocatable :: both
integer, allocatable, dimension(:) :: intcls
integer :: i

lt = len_trim(test)
allocate(isa(lt))
allocate(intcls(lt+1))
allocate(character(len=lt+1) :: both)
isa = .false.
both = class//trim(test)
do i = 1,lt+1
  select case (both(i:i))
    case ('A':'Z'); intcls(i) = 1! uppercase alphabetic
    case ('a':'a'); intcls(i) = 2! lowercase alphabetic
    case ('0':'9'); intcls(i) = 3! numeral
    case default;   intcls(i) = 99! checks if they are equal
  end select
end do
isa = intcls(1).eq.intcls(2:)

return
end function isa

end module that_has_function
!====== CALLER PROGRAM ======!
program that_uses_module
use that_has_function
implicit none
integer :: i
i = 65

! Reducing the result of "isa" to a scalar with "all" works:
!         V-V
do while (all(isa(achar(i),'A')))
  print*, achar(i)
 i = i + 1
end do

! Without the reduction it doesn''t:
!do while (isa(achar(i),'A'))
!  print*, achar(i)
! i = i + 1
!end do

end program that_uses_module

例如,我想在 do while 循环中使用此函数,如上面的代码所示。

问题是,例如,当我使用两个标量(等级 0)作为输入时,该函数仍将结果作为数组(等级 1)返回,因此为了使其作为 do while 循环的条件工作,我必须减少例如,结果为带有 all 的标量。

我的问题是:我可以让函数有条件地返回一个标量吗?如果不是,那么是否可以使函数与向量和标量输入一起工作并分别返回向量和标量输出?

1.我这里所说的类是,例如大写或小写字母,或数字等。 ↩

最佳答案

您不能使函数有条件地返回标量或向量。

但是你猜对了,有一个解决方案。您将使用通用函数。

您编写了 2 个函数,一个采用标量并返回标量 isas ,第二个采用向量并返回向量 isav

从模块外部,您将能够使用相同的名称调用它们: isa 。你只需要在模块的开头写出它的接口(interface):

module that_has_function
implicit none
public

interface isa
    module procedure isas, isav
end interface isa

contains
...

isa 被调用时,编译器会根据参数的类型知道使用哪个。

关于string - 根据输入返回标量或数组的 Fortran 函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49014237/

10-11 22:10
查看更多