Fortran
Modules and Derived Types
Organize code with modules and OOP-style types.
By EZ4Code Team
moduletypeoop
Code
module geometry
implicit none
private
public :: point_type, distance
type :: point_type
real :: x = 0.0, y = 0.0
contains
procedure :: dist_to_origin
end type
contains
function distance(p1, p2) result(d)
type(point_type), intent(in) :: p1, p2
real :: d
d = sqrt((p1%x - p2%x)**2 + (p1%y - p2%y)**2)
end function
function dist_to_origin(self) result(d)
class(point_type), intent(in) :: self
real :: d
d = sqrt(self%x**2 + self%y**2)
end function
end module
! Usage
program use_geom
use geometry
type(point_type) :: a, b
a%x = 0; a%y = 0
b%x = 3; b%y = 4
print *, distance(a, b) ! 5.0
print *, b%dist_to_origin()! 5.0
end programExplanation
Modules encapsulate types, procedures, and variables. private/public controls visibility. Derived types with contains support type-bound procedures (OOP). Use % to access components (like . in C++). class() (polymorphic) allows subclasses; type() is static. Always use implicit none to catch typos.
More Fortran Snippets
Arrays and Vector Operations
Create and operate on arrays in modern Fortran.
Subroutines and Functions
Define reusable procedures in Fortran.
File I/O and Formatting
Read/write files with formatted output.
OpenMP Parallelism
Parallelize loops with OpenMP directives.
Numerical: Linear Algebra (BLAS/LAPACK)
Call BLAS/LAPACK for matrix operations.
Derived Types and Pointers
Custom types with allocatable components and pointers.