Sunday 1 May 2016

Haskell: Qualified imports


In previous post, I explained how to create a module, how to import a module. In this post, I am going to explain about the need of qualified imports.

For example, you had 2 modules, Module1, Module2. Each module has a function 'processData x'.

Module1.hs
module Module1 where
    processData :: Integer -> Integer
    processData x = 10 * x


Module2.hs
module Module2 where
    processData :: Integer -> Integer
    processData x = 100 * x


test.hs
import Module1
import Module2

processInfo :: Integer -> Integer
processInfo x = processData x


test.hs imports both the modules Module1, Module2. processInfo method is calling processData method, which is exist in both the modules Module1, Module2. There is an ambiguity, Haskell don’t have any clue to call processData method. When you try to load test.hs, it will fail.
*Module1> :load test.hs
[1 of 3] Compiling Module2          ( Module2.hs, interpreted )
[2 of 3] Compiling Module1          ( Module1.hs, interpreted )
[3 of 3] Compiling Main             ( test.hs, interpreted )

test.hs:5:17:
    Ambiguous occurrence processData
    It could refer to either Module1.processData,
                             imported from Module1 at test.hs:1:1-14
                             (and originally defined at Module1.hs:3:5-15)
                          or Module2.processData,
                             imported from Module2 at test.hs:2:1-14
                             (and originally defined at Module2.hs:3:5-15)
Failed, modules loaded: Module1, Module2.
*Module1>


How to solve above problem?
By using qualified imports we can solve above problem.

Syntax
Import qualified ModuleName

test.hs
import qualified Module1
import qualified Module2

processInfo :: Integer -> Integer
processInfo x = Module1.processData x

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


You can solve above problem, simply calling the function using the Module name. No need to qualified imports.

test.hs
import Module1
import Module2

processInfo :: Integer -> Integer
processInfo x = Module1.processData x

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



Previous                                                 Next                                                 Home

No comments:

Post a Comment