In previous post, I explained the use of
qualified imports. IN this post, I am going to explain about the usage of
hiding definitions.
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 wants to use processData method of Module1,
but processData method 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?
One way to solve this problem is using
qualified imports, I already explained in previous post. Other way to solve the
problem is by hiding the function definition of Module2.
Syntax
Import ModuleName hiding (function1, …
functionN)
test.hs
import Module1 import Module2 hiding(processData) processInfo :: Integer -> Integer processInfo x = 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>
No comments:
Post a Comment