Beliavsky / FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip
https://zmoon.github.io/FortranTipBrowser/
The Unlicense
64 stars 14 forks source link

Tip: derived types can be used where scalars are required #30

Open Beliavsky opened 2 years ago

Beliavsky commented 2 years ago

An instance of a derived type is a scalar, even if it has array or pointer components. A derived type can be used where a scalar is required, for example as the dummy argument of an elemental procedure. Arrays of arrays or pointers can thus be simulated.

module m
implicit none
type :: vec
   real, allocatable :: x(:)
end type vec
contains
function ran(n) result(xran)
integer, intent(in) :: n
real :: xran(n)
call random_number(xran)
end function ran
!
elemental function moment(v,m) result(xmom)
! return the nth moment of the array component of v
type(vec), intent(in) :: v
integer  , intent(in) :: m
real                  :: xmom
real                  :: xmean
integer               :: n
n = max(1,size(v%x))
xmean = sum(v%x)/n
xmom  = sum((v%x-xmean)**m)/n
end function moment
end module m
!
program main
use m, only: moment,vec
implicit none
type(vec) :: v
character (len=20) :: fmt = "(a6,*(f8.4))"
v = vec(x = ran(10**4))
print fmt,"sim",moment(v,[1,2,3,4])
print fmt,"true",0.0,1/12.0,0.0,1/80.0
end program main
! sample output:
!    sim -0.0000  0.0833  0.0001  0.0124
!   true  0.0000  0.0833  0.0000  0.0125