如何在haskell中仅导入特定实例
我面临以下问题:我在一个模块中定义了一个类型类的多个实例,但不想导出所有这些实例。我怎样才能做到这一点?
module SomeModule
( calculate
)
where
class Something a where
calculate :: a -> Int
instance Something Double where
calculate x = calculate $ roundToInt x
instance Something Int where
calculate x = doSomething x
roundToInt :: Double -> Int
roundToInt = round
doSomething :: Int -> Int
doSomething _ = 42
在这个(简化的)示例中,我有两个Something相互依赖的类型类实例,但我只想导出Doubles 而不是Ints的实例。但在我的示例中,两个实例都被隐式导出。有办法解决吗?
回答
您可以将要隐藏的实例设置在newtype未导出的实例上。
module SomeModule (calculate) where
newtype NotInt = NotInt Int
class Something a where calculate :: a -> Int
instance Something Double where calculate x = calculate (NotInt (round x))
instance Something NotInt where calculate _ = 42
如果您不想导出许多实例,则参数化的 newtype 可能较少样板。
{-# LANGUAGE FlexibleInstances #-}
module SomeModule (calculate) where
newtype Hidden a = Hidden a
class Something a where calculate :: a -> Int
instance Something Double where calculate x = calculate (Hidden (round x :: Int))
instance Something (Hidden Int) where calculate _ = 42
另一种选择是不首先定义实例,只需使用与类的方法名称不同的名称来实现您关心的其他方法。
module SomeModule (calculate) where
class Something a where calculate :: a -> Int
instance Something Double where calculate x = calculateInt (round x)
calculateInt :: Int -> Int
calculateInt _ = 42