导入数据构造函数而不导入类型

时间:2016-09-10 23:37:38

标签: haskell import

numeric-prelude执行此操作,其中每个数据类型都命名为T,并且每个类型类都命名为C。为了......一致性,我想我会一起玩:

{-# LANGUAGE NoImplicitPrelude #-}
module Number.SqrtRatio (T(..), ratioPart) where

import qualified Number.Ratio as Ratio
import Number.Ratio ((:%))

import qualified Algebra.Ring as Ring
import NumericPrelude.Base

-- | A number whose square is rational, canonicalized as a rational
--   times the square root of a squarefree integer.
data T x = T {
    numerator :: !x,
    denominator :: !x,
    rootNum :: !x
    } deriving (Eq, Show)

ratioPart :: T x -> Ratio.T x
ratioPart (T n d _) = n :% d

fromRatio :: (Ring.C x) => Ratio.T x -> T x
fromRatio (n :% d) = T n d Ring.one

ghc没有留下深刻印象:

Number/SqrtRatio.hs:5:22:
    In module ‘Number.Ratio’:
      ‘(:%)’ is a data constructor of ‘T’
    To import it use
      ‘import’ Number.Ratio( T( (:%) ) )
    or
      ‘import’ Number.Ratio( T(..) )

当然,伙计,我可以遵守:

{-# LANGUAGE NoImplicitPrelude #-}
module Number.SqrtRatio (T, ratioPart) where

import qualified Number.Ratio as Ratio
import Number.Ratio (T((:%)))
--       newly added ^

...但是这也会导致导入Ratio.T,这与我的T冲突!

ratioPart :: T x -> Ratio.T x
{-           ^-- Ambiguous occurrence ‘T’
    It could refer to either ‘Number.SqrtRatio.T’,
                             defined at Number/SqrtRatio.hs:11:1
                          or ‘Number.Ratio.T’,
                             imported from ‘Number.Ratio’ at Number/SqrtRatio.hs:5:22-28
-}

好的,import Number.Ratio (T((:%))) hiding T怎么样?

Number/SqrtRatio.hs:5:31: parse error on input ‘hiding’

我有点失落,嘲笑。 :/

2 个答案:

答案 0 :(得分:8)

原来 是一种正确的方法:

{-# LANGUAGE NoImplicitPrelude, PatternSynonyms #-}
module Number.SqrtRatio (T(..), ratioPart) where

import qualified Number.Ratio as Ratio
import Number.Ratio (pattern (:%))

请注意,我已使用-XPatternSynonyms扩展程序不实际定义任何模式同义词,只是为了启用pattern关键字,以便明确我要导入值构造函数 :%

答案 1 :(得分:3)

我目前的解决方案,在发布前发现:

  • 放弃尝试导入(:%)
  • 保留合格的导入。
  • :%更改为Ratio.:%无处不在(模式和表达式)。

结果:

{-# LANGUAGE NoImplicitPrelude #-}
module Number.SqrtRatio (T(..), ratioPart) where

import qualified Number.Ratio as Ratio

import qualified Algebra.Ring as Ring
import NumericPrelude.Base

-- | A number whose square is rational, canonicalized as a rational
--   times the square root of a squarefree integer.
data T x = T {
    numerator :: !x,
    denominator :: !x,
    rootNum :: !x
    } deriving (Eq, Show)

ratioPart :: T x -> Ratio.T x
ratioPart (T n d _) = n Ratio.:% d

fromRatio :: (Ring.C x) => Ratio.T x -> T x
fromRatio (n Ratio.:% d) = T n d Ring.one

难看。