You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fortran 2008中方括号初始化数组的秩及代码合规性问询

Fortran代码疑问解答:数组构造器与标准合规性

先看你提供的代码:

module m
  implicit none

  type t
     integer, allocatable, dimension(:) :: r
  end type t

contains

  function tt(a,b)
    implicit none
    type(t), allocatable, dimension(:) :: tt
    type(t), intent(in), dimension(:) :: a,b
    allocate(tt, source = [a,b])     ! Is this square bracket correct ?
    return
  end function tt

  function ts(arg)
    implicit none
    type(t), allocatable, dimension(:) :: ts
    integer, intent(in) :: arg(:)
    allocate(ts(1))
    allocate(ts(1)%r, source = arg)
    return
  end function ts
end module m

program p
  use m
  implicit none
  type(t), dimension(2) :: c
  c=tt(ts([99,199,1999]),ts([42,142]))
  if (any (c(1)%r .ne. [99,199,1999])) STOP 1
  if (any (c(2)%r .ne. [42,142])) STOP 2
end program p

针对你的疑问逐一解答:

1. [a,b]是什么?

这是Fortran的数组构造器,作用是把多个同类型、同秩的数组或单个元素拼接成一个新数组。这里a和b都是一维的t类型数组,[a,b]会按顺序把a的所有元素放在前面,b的所有元素跟在后面,生成一个新的一维t类型数组。比如你调用tt(ts([99,199,1999]),ts([42,142]))时,a和b都是长度为1的t数组,[a,b]就变成了长度为2的一维t数组。

2. [a,b]的秩是多少?

秩是1(一维)。因为a和b本身都是一维数组,用数组构造器拼接同秩数组后,结果的秩和原数组一致,不会发生变化。

3. 是否与返回值tt匹配?

完全匹配。tt是可分配的一维t类型数组,[a,b]也是一维t类型数组,两者类型兼容、秩相同,完全满足allocate(..., source=...)的参数要求。

4. 代码是否符合Fortran 2008标准?

先把你引用的Fortran 2008标准条款翻译成中文:

每个分配对象(allocate-object)应与源表达式(source-expr)类型兼容(4.3.1.3)。若出现SOURCE=,源表达式应为标量,或与每个分配对象具有相同的秩。

对照这条标准分析:

  • 分配对象tt是一维t类型数组,源表达式[a,b]也是一维t类型数组,类型完全兼容,秩也相同,满足条款要求。
  • 同时,Fortran 2008明确允许用数组构造器拼接同类型、同秩的数组,所以[a,b]的写法本身也是合规的。

综上,这段代码完全符合Fortran 2008标准。

内容的提问来源于stack exchange,提问作者Billy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:40:35