Fundamentals of Modules

Introduction

A module is a technique of creating a certain section of code, for any reason. This allows you to have different sections in the program.

The goal of using modules is to create sections of code so as to use names that can be duplicated in different modules in the same program without danger for a name conflict.

Creating a Module

Like a function or a class, a module is simply a section of code in a regular F# file. The formula to create a module is:

module module-name
    [ begin ]
	body
    [ end ]

You start with the module keyword followed by a name. The name of the module follows the rules of names of classes. There are two categories of modules. If you want the whole content of a document to belong to one and the same module, on the first line of code (without a comment), simply create the module and continue your code on the next line. This type is called a top-level module. Normally, when you create a file and type code in it, the compiler internally creates a default module and considers that all the code in the document belongs to that default module.

Most of the time, you want a module if you need to create different sections of code in the same document. In this case, you create a module in/for each section. Such a module is called a local module. The formula to create a local module is:

module module-name =
    [ begin ]
	body
    [ end ]

In this case, you must add = after the name of the module. The code of the module starts on the next line.

The Body of a Module

The section after the name of a top-level module or after the = symbol of a local module is referred to as the body of the module. The body of the module can start with the begin keyword in which case it must end with the end keyword. If you decide to include the body of the module between a beginning and ending lines, the begin and the end keywords must be indented from the level of the module keyword. Then the body section must be indented from the begin and end level. If you decide to omit the begin and end keywords, then the modul's body must be indented from the level of the module keyword.

The body of a module can practically contain any type of code we have used in previous lessons. Here is an example:

module Exercise =
    begin
        printfn "Welcome to the wonderful world of functional programming!";
    end

In the same way, inside the document, you can create as many modules as you want.

module Annoucement =
    begin
        printfn "Welcome to our wonderful county library!!!";
    end

module LibraryMembership =
    let mutable age = 12;

    if age < 18 then
        printfn "The person is less than 18 years old.";
    else
        printfn "This person is not younger than 18."

module LibraryDatabase =
    let mutable age = 12;

    age <- 36;

    if age < 18 then
        printfn "The person is less than 18 years old.";
    else
        printfn "This person is not younger than 18."

Notice that two modules have a variable with the same name. Because they belong to different sections, there is no name conflict.

Using Modules

Referring to Members of a Module

You can refer to a member of one module inside another module. In this case, you must qualify the name of the member from its parent module. To do this where needed, type the name of the module, followed by a period, and followed by the name of the member. Here are examples:

module CommercialBank =
    let employeeName = "Frank Nahor"
    let employeePhone = "102-929-3804"
    
module CarDealership =
    let employeeName = "Jeremy Willing"
    let emailAddress = "jwilling@hotmail.com"
    let vehiclePrice : int = 26780;

module VehicleFinancing =
    let interestRate = 16.85
    let datePaymentsStart = "Next Month"
    
    printfn "Financing Summary"
    printfn "-------------------"
    printfn "Loan processed by: %s (%s)" CarDealership.employeeName CarDealership.emailAddress
    printfn "Loan approved by:  %s, %s" CommercialBank.employeeName CommercialBank.employeePhone
    printfn "Vehicle Price:     $%d" CarDealership.vehiclePrice
    printfn "Interest Rate:     %0.02f" interestRate
    printfn "Payments Start:    %s" datePaymentsStart

This would produce:

Vehicle Financing Summary
-------------------
Loan processed by: Jeremy Willing (jwilling@hotmail.com)
Loan approved by:  Frank Nahor, 102-929-3804
Vehicle Price:     $26780
Interest Rate:     16.85
Payments Start:    Next Month

Press any key to continue . . .

Nesting a Module

One module can be created in the body of another module. This is referred to as nesting a module. Here is an example:

module Geometry =

    printfn "Geometry is the branch of mathematics that studies shapes, figures, and space."

    module Polygons =
        type Square() =
            member this.Describe() =
                printfn "A square is a quadrilateral with four equal sides and four equal angles of 90 degrees."

The outside module that contains the second module is referred to as nesting. The module inside of another is referred to as nested. Any of those modules can contain any type of member. In the same way, any module can contain its own modules.

To access a member of a module outside its parent, you must fully qualify its name. Here are example:

module Geometry =
    printfn "Geometry is the branch of mathematics that studies shapes, figures, and space."
    
    module Polygons =
        type Square() =
            member this.Describe() =
                printfn "A square is a quadrilateral with four equal sides and four equal angles of 90 degrees."
        type Triangle() =
            member this.Describe() =
                printfn "A triangle is a polygon that has three edges and three vertices."
    module Planes =
        type Circle(radius) =
            do
                printfn "A circle is a shape of all point that are at an equal distance from another point named the center."
        type Ellipse(largeRadius, smallRadius) =
            member this.Describe() =
                printfn "An ellipse is curved plane with two focal points."
module Trigonometry =
    type Triangle() =
        member this.Describe() =
            printfn "A triangle is a plane shape from three leveled points."

module Summary =
    printf "Triangular Polygon Definition: "
    let geo = Geometry.Polygons.Triangle()
    geo.Describe()
    printf "Trigonometric Triangle Definition: "
    let tri = Trigonometry.Triangle()
    tri.Describe()

This would produce:

Geometry is the branch of mathematics that studies shapes, figures, and space.
Triangular Polygon Definition: A triangle is a polygon that has three edges and three vertices.
Trigonometric Triangle Definition: A triangle is a plane shape from three leveled points.

Press any key to continue . . .

Previous Copyright © 2014-2024, FunctionX Monday 14 February 2022 Next