functorオブジェクトを定義して基本的に(Vladimir's answerでも言及されているように)行うことができます。それらは値を返す1つの特定の関数(たとえばgetvalue()
)を持ち、初期化によってはカスタマイズされた関数値を返すことがあります。
以下の例は、その詳細を示しています。一般ファンクタはfunctor_module
で定義され、expfunc_module
では指数関数ファミリの具体的な実現が導出されます。次に、メインプログラムで指数部の異なるプリ係数を持つ異なるインスタンスを初期化し、適切な関数値を得るためにgetvalue()
メソッドを使用することができます。:
module functor_module
implicit none
integer, parameter :: wp = kind(1.0d0)
type, abstract :: functor
contains
procedure(getvalue_iface), deferred :: getvalue
end type functor
interface
function getvalue_iface(self, xx) result(yy)
import
class(functor), intent(in) :: self
real(wp), intent(in) :: xx
real(wp) :: yy
end function getvalue_iface
end interface
end module functor_module
module expfunc_module
use functor_module
implicit none
type, extends(functor) :: expfunc
real(wp) :: aa
contains
procedure :: getvalue
end type expfunc
contains
function getvalue(self, xx) result(yy)
class(expfunc), intent(in) :: self
real(wp), intent(in) :: xx
real(wp) :: yy
yy = exp(self%aa * xx)
end function getvalue
end module expfunc_module
program test_functors
use expfunc_module
implicit none
type(expfunc) :: func1, func2
real(wp) :: xx
func1 = expfunc(1.0_wp)
func2 = expfunc(2.0_wp)
xx = 1.0_wp
print *, func1%getvalue(xx) ! gives exp(1.0 * xx) = 2.718...
print *, func2%getvalue(xx) ! gives exp(2.0 * xx) = 7.389...
end program test_functors