Simon Fromme
Simon Fromme

Reputation: 3174

Operator shadowing in Haskell

I want to use the <|> operator from Text.Parsec but I am also importing Control.Applicative which also contains a <|> operator. How do I make sure that the former operator shadows the latter assuming I don't want to use an ugly looking qualified import?

Upvotes: 1

Views: 268

Answers (2)

epsilonhalbe
epsilonhalbe

Reputation: 15967

The proper way to do this would either be a qualified import or an import with hiding

import qualified Control.Applicative as CA
import Text.Parsec

or if you don't want to use qualified

import Control.Applicative hiding ((<|>))
import Text.Parsec

Shadowing would not work because both imports live in the same namespace and therefore ghc cannot infer the correct choice of function, i.e. the one you meant.

To my knowledge shadowing only works in function blocks which generate a new scope.

Moreover the order of imports makes in a lazily evaluated language has its perils and even though I am no expert I would guess that if a library is imported depends whether if it is used or where it is used which would affect the order of import.

update:

If there was a name shadowing at the point of imports - then the order of imports would make a difference, which is something you are not used to in a lazily evaluated language, where usually the order of execution of pure functions is arbitrary (even though the imports are done at compile time as @TikhonJelvis pointed out).

Upvotes: 2

leftaroundabout
leftaroundabout

Reputation: 120711

Options you have, in descending order of recommendation:

  • Switch to megaparsec, which is built up front around the existing Haskell functor / transformer classes, rather than defining that kind of stuff anew.
  • Hide the unnecessarily specific Parsec.<|>. You don't need it.

    import Text.Parsec hiding ((<|>))
    import Control.Applicative
    
  • Hide Applicative.<|> and use only the stuff from Control.Applicative that's not concerned with alternatives.

    import Text.Parsec
    import Control.Applicative hiding (Alternative(..))
    

Upvotes: 7

Related Questions