プログラム中で1から10までの整数列が欲しくなることがありますが[(i, i = 1, 10)]と配列生成子でつくるのも、捨て変数 i を宣言しないといけないので面倒です。Haskell のように 1..10 のように生成できるとうれしいのですが、Fortranならユーザー定義演算子で似たようなことができます。
また、配列型の返り値をもった関数で、その中の特定要素のみを取り出す演算子が欲しいことがありますが、それもユーザー定義演算子で実現できます。
ここでは、i0.to.i1 の形で整数列を生成します。(本当はFortran特有の三つ組み 1:10:1 の形でステップも含めて書けるとありがたいのですが。
配列要素の取り出しは、後置演算子の形で [....] .p. n の形で n 番目の要素を取り出します。
ソース・プログラム
module m_op implicit none interface operator(.to.) module procedure opfun end interface interface operator(.p.) module procedure array_i, array_r end interface contains function opfun(i0, i1) result(res) integer, intent(in) :: i0, i1 integer :: res(abs(i1 - i0 + 1)) integer :: i res = [(i, i = i0, i1, sign(1, i1 - i0))] return end function opfun integer function array_i(ia, n) integer, intent(in) :: ia(:), n array_i = ia(n) return end function array_i real function array_r(ra, n) real, intent(in) :: ra(:) integer, intent(in) :: n array_r = ra(n) return end function array_r end module m_op program main use m_op implicit none print *, 1.to.10 print *, sum( 1.to.10 ) print *, sqrt(real(1.to.15)) print *, sqrt(real(1.to.15)) .p. 5 stop end program main