mljrg
mljrg

Reputation: 4620

GHC import feature or bug

I found that the following code is accepted by GHC:

import Prelude hiding (filter)
import qualified Prelude as P

The idea of these two imports is to make all Prelude functions available as usual, but to require filter to be qualified as P.filter.

I never saw a similar example anywhere, hence my question: is this a feature or a bug in GHC?

Thanks

Upvotes: 4

Views: 73

Answers (2)

chi
chi

Reputation: 116139

This is allowed. The import mechanism is very flexible, sometimes surprisingly so.

You can for instance import a module under different names:

import qualified M as A
import qualified M as B

After this, both A.x and B.x will refer to M.x.

Perhaps more surprisingly, you can also import two modules under the same name.

import qualified M as A
import qualified N as A

After this, A.x will refer to either M.x or N.x. If both are defined, an ambiguity error is triggered.

This last feature might seem strange, but after all such ambiguities are already present when importing modules without qualification, so this flexibility does not require any more machinery than the plain import does.

Upvotes: 3

osa1
osa1

Reputation: 7078

This is a feature and if you search in Github for example you can see this used a lot in the wild.

A widely used idiom is this:

import Data.Text (Text)
import qualified Data.Text as T

This way you don't have to qualify Text in your types and you don't get functions that are conflicting with Prelude functions(like Data.Text.filter, Data.Text.zip etc.).

Upvotes: 3

Related Questions