Dynamic function creation from another function

前端 未结 2 1700

I have a Fortran 90 subroutine which takes a function as an argument, and I would like to pass a modified version of that function into another subroutine. I want the progra

相关标签:
2条回答
  • 2020-12-20 19:10

    This is not so easy. In some languages you can pass pointers to nested functions in a so called closure. This is not possible in Fortran (or C and similar languages), because the data are destroyed with the stack of the higher function. I would suggest you to try function objects, i.e. a class with a function pointer (or more) and data needed for the function. In this way you can even do function composition and similar functional stuff.

    More on the concept http://en.wikipedia.org/wiki/Function_object

    Below is a sample for a function object for composition of two single argument functions:

    module ComposeObj
      use Parameters, only: rp
      use AritmFunctions, only: fce
      implicit none
    
      private
      public Compose
    
      type Compose
        private
        procedure(fce),pointer,nopass :: f1 => null(),f2=>null()
      contains
        procedure,public :: call => helper
      end type Compose
    
      interface Compose
        procedure NewCompose
      end interface
    
     contains
    
      function NewCompose(f,g)
        procedure(fce) :: f,g
        type(Compose) :: NewCompose
    
        NewCompose%f1 => f
        NewCompose%f2 => g
      end function NewCompose
    
      pure real(rp) function helper(this,x)
        class(Compose),intent(in) :: this
        real(rp),intent(in) :: x
        helper = this%f1(this%f2(x))
      end function helper
    
    end module ComposeObj
    
    0 讨论(0)
  • 2020-12-20 19:24

    You could do a lot with procedure pointers, constructing a function that is a combination of other functions. See Function pointer arrays in Fortran for a code example.

    0 讨论(0)
提交回复
热议问题