代码之家  ›  专栏  ›  技术社区  ›  LennyStackOverflow

当前模块是否有命名空间?

  •  2
  • LennyStackOverflow  · 技术社区  · 14 年前

    module A where
    
    data A = A { f :: Int }
    
    defaultA = A { f = 0 }
    

    module B where
    
    import A as A
    
    data B = B { f :: Int }
    
    bToA :: B -> A
    bToA x = defaultA { A.f = f x }
    

    B.hs:8:26:
        Ambiguous occurrence `f'
        It could refer to either `B.f', defined at B.hs:5:13
                              or `A.f', imported from A at B.hs
    

    由于我不能在自身中包含B限定,有什么替代方法可以解决名称空间冲突?我不想重命名冲突函数。

    编辑:更新了示例。

    3 回复  |  直到 14 年前
        1
  •  6
  •   sclv    14 年前
    import qualified A as A
    
        2
  •  5
  •   ADEpt    14 年前

    我会这样做:

    module B where
    
    import A hiding (A(..))
    import qualified A as A
    
    bToA x = defaultA { A.f = f x }
    

    这样,您就可以从A访问所有不冲突的名称,而不必在“A”前面加上前缀,并且所有冲突的名称都是以完全限定的形式导入的,即“A.something”。您可以保持代码的简洁性并解决冲突。

    当然,简单点 import qualified Some.Long.Name as S 如果你不介意在任何地方都准备“S”的话,也可以。

        3
  •  2
  •   Yuras    14 年前

    只是 B.f

    你不需要

    import A as A
    

    只是

    import A