Sunday 1 May 2016

Haskell: Renaming imports


If your module name is very big like Chapter1Excercises1, and if you are doing qualified imports, then you must call the function name using the Module name like Chapter1Excercises1.functionName, it is irritating right.

We can improve things by using the as keyword:

Chapter1Excercises1.hs
module Chapter1Excercises1 where
    addition :: Integer -> Integer -> Integer   
    addition x y = (x+y)

  test.hs
import qualified Chapter1Excercises1 as C1E1

processInfo :: Integer -> Integer -> Integer
processInfo x y = C1E1.addition x y

Prelude> :load test.hs
[1 of 2] Compiling Chapter1Excercises1 ( Chapter1Excercises1.hs, interpreted )
[2 of 2] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main, Chapter1Excercises1.
*Main> 
*Main> processInfo 10 20
30
*Main> 

  This renaming works with both qualified and regular imports.

test.hs
import Chapter1Excercises1 as C1E1

processInfo :: Integer -> Integer -> Integer
processInfo x y = C1E1.addition x y


Can I import multiple modules and rename them the same?
Yes, as long as there is no conflicting items, you can import multiple modules and rename them same.

Chapter1Excercises1.hs
module Chapter1Excercises1 where
    addition :: Integer -> Integer -> Integer   
    addition x y = (x+y)


Chapter1Excercises2.hs
module Chapter1Excercises2 where
    subtraction :: Integer -> Integer -> Integer   
    subtraction x y = (x-y)


test.hs
import Chapter1Excercises1 as Exer
import Chapter1Excercises2 as Exer

processInfo :: Integer -> Integer -> Integer
processInfo x y = Exer.addition x y + Exer.subtraction x y

*Main> :load test.hs
[1 of 3] Compiling Chapter1Excercises2 ( Chapter1Excercises2.hs, interpreted )
[2 of 3] Compiling Chapter1Excercises1 ( Chapter1Excercises1.hs, interpreted )
[3 of 3] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main, Chapter1Excercises1, Chapter1Excercises2.
*Main> 
*Main> processInfo 10 20
20
*Main>

Previous                                                 Next                                                 Home

No comments:

Post a Comment