Skip to content

Instantly share code, notes, and snippets.

@shintakezou shintakezou/generic.f90
Last active Aug 7, 2018

Embed
What would you like to do?
Type-generic functions' example in Fortran90
program generic_example
use my_sum_module
implicit none
print *, my_sum(1.0, 3.0) ! 1 + 1.5
print *, my_sum(1, 5) ! 1 + 2
print *, my_sum(2, 3.0) ! 2 + 1.5
print *, my_sum(1.5, 7) ! 1.5 + 3.5
! 1 + 1, (1 + 2)/2 (1.5)
print *, my_sum(something(1,1), something(1,2))
! the following halts compilations, since
! There is no specific function for the generic 'my_sum'
!print *, my_sum(something(1,1), 5.0)
end program generic_example
module my_sum_module
implicit none
! interfaces are generated from the function themselves
interface my_sum
module procedure my_sum_r, my_sum_i, my_sum_v, &
my_sum_m1, my_sum_m2
end interface
type, public :: something
real :: x, y
end type something
contains
function my_sum_r(x, y)
implicit none
real, intent(in) :: x, y
real :: my_sum_r
my_sum_r = x + y/2.0
end function my_sum_r
function my_sum_m1(x, y)
implicit none
integer, intent(in) :: x
real, intent(in) :: y
real :: my_sum_m1
my_sum_m1 = real(x) + y/2.0
end function my_sum_m1
function my_sum_m2(x, y)
implicit none
integer, intent(in) :: y
real, intent(in) :: x
real :: my_sum_m2
my_sum_m2 = x + real(y)/2.0
end function my_sum_m2
function my_sum_i(x, y)
implicit none
integer, intent(in) :: x, y
integer :: my_sum_i
my_sum_i = x + y/2
end function my_sum_i
function my_sum_v(x, y)
implicit none
type(something), intent(in) :: x, y
type(something) :: my_sum_v
my_sum_v%x = x%x + y%x
my_sum_v%y = (x%y + y%y)/2.0
end function my_sum_v
end module my_sum_module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.