I would like to define a derived type containing a callback function (subroutine) as a member.
For example, problem
is a derived type that defines an optimization problem. It contains objective
, n
, and x0
as the members. I imagine it will be implemented as follows.
type problem
integer :: n
real, allocatable :: x0(:)
procedure(FUN) :: objective ! Should this be a pointer?
end type problem
Here, objective
is a callback function (subroutine) with the following interface.
abstract interface
subroutine FUN(x, f)
implicit none
real, intent(in) :: x(:)
real, intent(out) :: f
end subroutine FUN
end interface
Now suppose that I would like to construct an instance of problem
. In particular, I would like to set objective
to the following subroutine.
subroutine qua(x, f)
implicit none
real, intent(in) :: x(:)
real, intent(out) :: f
f = sum(x**2)
end function
How should this be implemented? Thank you very much.