Name conflicts in Haskell records

前端 未结 3 1505
生来不讨喜
生来不讨喜 2020-12-08 04:41

Haskell doesn\'t have dot notation for record members. For each record member a compiler creates a function with the same name with a type RecType -> FieldType. This leads

3条回答
  •  独厮守ぢ
    2020-12-08 05:18

    For large projects, I prefer to keep each type in its own module and use Haskell's module system to namespace accessors for each type.

    For example, I might have some type A in module A:

    -- A.hs
    
    data A = A
        { field1 :: String
        , field2 :: Double
        }
    

    ... and another type B with similarly-named fields in module B:

    -- B.hs
    
    data B = B
        { field1 :: Char
        , field2 :: Int
        }
    

    Then if I want to use both types in some other module C I can import them qualified to distinguish which accessor I mean:

    -- C.hs
    import A as A
    import B as B
    
    f :: A -> B -> (Double, Int)
    f a b = (A.field2 a, B.field2 b)
    

    Unfortunately, Haskell does not have a way to define multiple name-spaces within the same module, otherwise there would be no need to split each type in a separate module to do this.

提交回复
热议问题