Sunday, 1 May 2016

Haskell: Modules: Restrict functions to expose


Suppose your module has 100 functions, and you want to expose only 10 out of 100 functions.

How can you do this?
Following statement expose only function1, function2 to outside world.

module MyModule (function1, function2) where

Above statement expose only function1, function2 of the module MyModule.

Example
NumberUtil.hs
module NumberUtil (dropLastDigit, getLastDigit) where

    {- Drop last digit -}
    dropLastDigit :: Integer -> Integer
    dropLastDigit num
        | (num < 0) = (-1) * (dropLastDigit ((-1) * num))
        | otherwise = processNum (num `div` 10) 0

    {- Return the last digit of a number -}
    getLastDigit :: Integer -> Integer
    getLastDigit num
        | (num < 0) = ((-1) * num) `rem` 10
        | otherwise = num `rem` 10

    processNum num temp
        | (num==0) = 0
        | otherwise = ((getLastDigit num) * (10 ^ temp)) + processNum (num `div` 10) (temp+1)


test.hs
import NumberUtil

removeLastDigit num = dropLastDigit num

getMeLastDigit num = getLastDigit num

processData num temp = processNum num temp


'test.hs' is using processNum function of Module NumberUtil, which is not exposed to outside world. So when you try to load test.hs, you will get error like ‘Not in scope: ‘processNum’’.
Prelude> :load test.hs
[1 of 2] Compiling NumberUtil       ( NumberUtil.hs, interpreted )
[2 of 2] Compiling Main             ( test.hs, interpreted )

test.hs:7:24: Not in scope: processNum
Failed, modules loaded: NumberUtil.
*NumberUtil>


Update test.hs by removing processData method, and reload test.hs.

test.hs
import NumberUtil

removeLastDigit num = dropLastDigit num

getMeLastDigit num = getLastDigit num

*NumberUtil> :load test.hs
[1 of 2] Compiling NumberUtil       ( NumberUtil.hs, interpreted )
[2 of 2] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: NumberUtil, Main.
*Main> 
*Main> removeLastDigit 123456
12345
*Main> 
*Main> getMeLastDigit 123456
6
*Main>


How to export data types and constructors?
Name the type, and follow with the list of value constructors in parenthesis.

TreeUtil.hs
module TreeUtil (Tree(Node, Empty)) where
    data Tree a = Node a (Tree a) (Tree a) 
                 | Empty 
                 deriving (Show)




Previous                                                 Next                                                 Home

No comments:

Post a Comment