0
\$\begingroup\$

I would like to write cleaner, reusable code in Fortran. Is the following piece of code a good way to implement generic functionality? Is the linebreaking and indentation ok? It should be Fortran90. The used compiler is GNU Fortran 5.4.0.

module geometry
    implicit none
    type circle
        real r
    end type circle

    type rectangle
        real a, b
    end type rectangle

    real, parameter :: PI = 3.1415

    private :: circle_area, rectangle_area
    interface area
        module procedure circle_area, rectangle_area
    end interface

contains

    real function circle_area(C)
        type(circle), intent(in) :: C
        circle_area = PI * C%r**2
    end function circle_area

    real function rectangle_area(R)
        type(rectangle), intent(in) :: R
        rectangle_area = R%a * R%b
    end function rectangle_area

end module


module extended_geometry
use geometry
    implicit none
    type square
        real a
    end type square

    private :: square_area
    interface area
        module procedure square_area
    end interface

contains

    real function square_area(S)
        type(square), intent(in) :: S
        square_area = area(rectangle(S%a, S%a))
    end function square_area

end module extended_geometry


program type_dispatch
use extended_geometry
    implicit none

    type(circle) :: C
    type(rectangle) :: R
    type(square) :: S

    S = square(a=2.0)
    C = circle(r=4.0)
    R = rectangle(a=1.0, b=2.0)

    print *, area(C)
    print *, area(R)
    print *, area(S)

end program type_dispatch
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.