2012-03-13 3 views
3

함수를 인수로 취하는 Fortran 90 서브 루틴을 가지고 있으며이 함수의 수정 된 버전을 다른 서브 루틴으로 전달하려고합니다. 프로그램이 다음과 같이 보이길 원합니다 :다른 함수에서 동적 함수 작성

subroutine foo(f, ...) 
    real     :: pt(2), dir(2) 

    interface 
    function f(x) result(y) 
     real, intent(in) :: x(2) 
     real    :: y 
    end function f 
    end interface 

    pt = ... 
    dir = ... 
!! Somehow create g(x) = f(pt + x*dir) 
    call bar(g) 

end subroutine foo 

subroutine bar(g) 
    interface 
    function g(x) result(y) 
     real, intent(in) :: x 
     real    :: y 
    end function g 
    end interface 

!! Do stuff with g 
end subroutine bar 

'g'는 함수가 아닌 일반 변수 만 사용해야 할 때 비슷한 일을했습니다. 이 경우 전역 변수를 사용하여 전역 함수로 만들고 'foo'에서 전역 변수에 할당했습니다. 그러나 'f'를 전역으로 설정하거나 전역 기능에 할당하는 방법을 찾을 수 없습니다.

아무도 아이디어를 가지고 어떻게해야합니까? 솔루션은 원하는대로 해킹 할 수 있습니다.

답변

1

프로 시저 포인터로 많은 작업을 수행하여 다른 기능을 조합 한 함수를 구성 할 수 있습니다. 코드 예제는 Function pointer arrays in Fortran을 참조하십시오.

4

이것은 그리 쉽지 않습니다. 일부 언어에서는 closure이라는 중첩 함수에 대한 포인터를 전달할 수 있습니다. 이것은 데이터가 상위 함수의 스택으로 파괴되기 때문에 Fortran (또는 C 및 유사한 언어)에서는 가능하지 않습니다. 함수 개체 (예 : function pointer (이상))와 함수에 필요한 데이터가 포함 된 class을 사용해 보시기 바랍니다. 이런 식으로 기능 구성과 비슷한 기능을 수행 할 수도 있습니다. 개념 아래 http://en.wikipedia.org/wiki/Function_object

더 두 하나의 인자 기능을 구성하는 기능 개체에 대한 샘플입니다 : 예에 대한

module ComposeObj 
    use Parameters 
    use AritmFunctions 
    implicit none 

    private 
    public Compose 

    type Compose 
    private 
    procedure(fce),pointer,nopass :: f1 => null(),f2=>null() 
    contains 
    procedure,public :: call => helper 
    endtype 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(KND) function helper(this,x) 
    class(Compose),intent(in) :: this 
    real(KND),intent(in) :: x 
    helper = this%f1(this%f2(x)) 
    end function helper 

end module ComposeObj 
+0

감사하지만, 포트란 90 일 것인가? 당신이 사용한 많은 키워드는 저에게 새롭다; 특히 저는 2003 년 90 세가 아니라 'procedure'에 대한 언급 만 찾을 수있었습니다. –