2011-09-06 123 views
2

在下面的子例程中,我想傳遞一個名爲str的字符串變量。如果它是'poly','gaus','slat',則它具有預定義的動作(fval =見代碼以下)。我想讓用戶指定一個函數來使用並將其作爲字符串變量傳遞。在Fortran子程序中傳遞字符串以執行

也就是說......

如果str = '3*cos(i*t)',那麼我想有fval等於3*cos(i*t)。如何讓Fortran將輸入的字符串解釋爲由Fortran執行的命令?

subroutine f(fval, i, t, str) 
implicit none 
integer, parameter :: ikind = selected_int_kind(8) 
integer, parameter :: dbl = selected_real_kind(15,307) 

integer(kind = ikind) :: i 
real(kind = dbl) :: fval, t 
character str*100 

if(str .eq. 'poly') then 
    fval = t**i 
elseif(str .eq. 'slat') then 
    fval = exp(-i*t) 
elseif(str .eq. 'gaus') then 
    fval = exp(-i*t*t) 
else 
    fval = ??? 
endif 

end subroutine 

回答

2

你不能。不容易。有兩件事你可以做,雖然:

+0

我會建議使用Lua,它很容易在Fortran應用程序中編譯並可用於評估字符串。也許https://bitbucket.org/haraldkl/aotus/overview可能會給你一個想法如何做到這一點。 – haraldkl

+0

我不認爲選項一會工作。這就是問題所在的「定義其他地方」。我希望這適用於任何函數作爲字符串輸入。至於你的第二選擇 - 我認爲這可能正是我所期待的! – drjrm3

-4

其實,這是很簡單

subroutine f(fval, i, t, str) ... character(len=*), intent(in) :: str ... end subroutine

關鍵是要界定「未知長度」的虛擬字符串參數,但帶有intent(in)修飾符。

+3

我認爲對這個問題的密切關注會表明這不是一個答案。該問題需要解決解析包含數學表達式的字符串的問題。 –