我有一个内部模块我想为
提供外部APImodule 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
我可以通过使用合格的导入来简化我的导入,但我很好奇。
有没有办法在单个import语句中导入除哑构造函数之外的所有Positive.Internal
?
我尝试了hiding (Positive(Positive))
,但是它隐藏了类型和哑构造函数。我对the wiki进行了探讨,但我还没有注意到在hiding
列表中区分构造函数和类型的方法。
答案 0 :(得分:3)
如果我错了,请纠正我,但我几乎可以肯定这就是你要找的东西:
{-# 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