隐藏一个构造函数,但不是导入时的类型

我有一个内部模块,我想为其提供一个外部API

module Positive.Internal where

newtype Positive a = Positive { getPositive :: a }
  deriving (Eq, Ord)

-- smart constructor
toPositive :: (Num a, Ord a) => a -> Maybe (Positive a)
toPositive a | a <= 0    = Nothing
             | otherwise = Just $ Positive a
-- ...

我想隐藏愚蠢的构造函数,并将其替换为单向模式,以便用户仍可以对匹配值进行模式化,只需使用智能构造函数即可使用新值。

因为我希望模式和愚蠢的构造函数使用相同的名称,所以我需要隐藏哑元构造函数以防止名称空间冲突。

然而,由于愚蠢的构造函数和类型共享名称,导入所有东西,但愚蠢的构造函数有点棘手。

目前我正在做这个,这很好:

{-# LANGUAGE PatternSynonyms #-}
module Positive
  ( module Positive.Internal, pattern Positive
  ) where

import Positive.Internal (Positive())
import Positive.Internal hiding (Positive)
import qualified Positive.Internal as Internal

pattern Positive :: a -> Positive a
pattern Positive a <- Internal.Positive a

我可以通过使用合格的导入来简化我的导入,但我很好奇。

有没有办法在单个导入语句中导入除了哑元构造函数之外的所有Positive.Internal

我试图hiding (Positive(Positive)) ,但是隐藏了类型和哑元构造函数。 我探讨了wiki,但我没有注意到在hiding列表中区分构造函数和类型的方法。


纠正我,如果我错了,但我几乎肯定这是你正在寻找的东西:

{-# LANGUAGE PatternSynonyms #-}
module Positive
  ( module Positive.Internal, pattern Positive, foo
  ) where

import Positive.Internal hiding (pattern Positive)
import qualified Positive.Internal as Internal (pattern Positive)

pattern Positive :: a -> Positive a
pattern Positive a <- Internal.Positive a

foo :: Positive Int
foo = Internal.Positive 5

Internal模块与目前定义的方式保持一致。 为了举例:

module Negative where

import Positive

bar :: Maybe Int
bar = getPositive <$> toPositive 6

让我们加倍检查GHCi:

Prelude> :load Negative
[1 of 3] Compiling Positive.Internal ( Positive/Internal.hs, interpreted )
[2 of 3] Compiling Positive         ( Positive.hs, interpreted )
[3 of 3] Compiling Negative         ( Negative.hs, interpreted )
Ok, modules loaded: Negative, Positive, Positive.Internal.
*Negative> bar
Just 6
*Negative> getPositive foo
5
*Negative> :i Positive
newtype Positive a = Positive.Internal.Positive {getPositive :: a}
    -- Defined at Positive/Internal.hs:3:1
instance [safe] Ord a => Ord (Positive a)
  -- Defined at Positive/Internal.hs:4:17
instance [safe] Eq a => Eq (Positive a)
  -- Defined at Positive/Internal.hs:4:13
*Negative> :t Positive

<interactive>:1:1: error:
    • non-bidirectional pattern synonym ‘Positive’ used in an expression
    • In the expression: Positive
链接地址: http://www.djcxy.com/p/39129.html

上一篇: Hide a constructor but not the type on import

下一篇: Emoji to PNG or JPG in Node.js