Sunday, 1 May 2016

Haskell: Modules


Module defines a collection of classes, types, constants, type synonyms etc. Module can import other modules using import statement.

How to define a module
By using following statement, you can define a module.

module ModuleName where

Following are the points to note while defining a module.
a.   Module name must start with capital letter.
b.   One file contains one module, Suppose your module “Arithmetic’ should be in Arithmetic.hs file
c.    The name of the file is name of the module followed by .hs extension.
d.   Any dots '.' in the module name are changed for directories. For example Math.Arithmetic would be in the file Math/Arithmetic.hs (In Open systems), Math\Arithmetic.hs in windows.

Arithmetic.hs
-- Arithmetic module implements simple Arithmetic functions
 module Arithmetic where
    addition :: Integer -> Integer -> Integer
    addition x y = (x+y)

    sub :: Integer -> Integer -> Integer
    sub x y = (x-y)

    mul :: Integer -> Integer -> Integer
    mul x y = (x*y)

    divide :: Integer -> Integer -> Double
    divide x y = (fromIntegral x / fromIntegral y)

Prelude> :load Arithmetic.hs
[1 of 1] Compiling Arithmetic       ( Arithmetic.hs, interpreted )
Ok, modules loaded: Arithmetic.
*Arithmetic> 
*Arithmetic> addition 10 20
30
*Arithmetic> 
*Arithmetic> sub 10 20
-10
*Arithmetic> 
*Arithmetic> mul 10 20
200
*Arithmetic> 
*Arithmetic> div 10 20
0
*Arithmetic> divide 10 20
0.5
*Arithmetic> 


Importing modules
Modules can be imported using import statement.

Syntax
import ModuleName
Import everything from given module.

import ModuleName (function1, function2 ... functionN)
Import specific functions from give module.

Example
import Data.List : Import everything from the module Data.List
import Data.List (length, head, tail) : Import lenght, head and tail functions from the module Data.List.

ArithmeticTest.hs
import Arithmetic

processData :: Integer -> Integer -> (Integer, Integer, Integer, Double)
processData a b  = ((addition a b), (sub a b), (mul a b), (divide a b))

Prelude> :load ArithmeticTest.hs
[1 of 2] Compiling Arithmetic       ( Arithmetic.hs, interpreted )
[2 of 2] Compiling Main             ( ArithmeticTest.hs, interpreted )
Ok, modules loaded: Arithmetic, Main.
*Main> 
*Main> let (addition, subtraction, multiplication, division) = processData 10 20
*Main> 
*Main> addition
30
*Main> subtraction
-10
*Main> multiplication
200
*Main> division
0.5





Previous                                                 Next                                                 Home

No comments:

Post a Comment