Avoiding namespace pollution in Haskell

前端 未结 5 1709
鱼传尺愫
鱼传尺愫 2020-12-04 10:46

I\'m using lots of different records in a program, with some of them using the same field names, e.g.

data Customer = Customer { ..., foo :: Int, ... }
data          


        
5条回答
  •  星月不相逢
    2020-12-04 11:13

    There's a language extension DuplicateRecordFields that allows duplication of field functions and makes its type to be inferred by type annotation.

    Here is a little example (haskell-stack script):

    #!/usr/bin/env stack
    -- stack runghc --resolver lts-8.20 --install-ghc
    
    {-# LANGUAGE DuplicateRecordFields #-}
    
    newtype Foo = Foo { baz :: String }
    newtype Bar = Bar { baz :: String }
    
    foo = Foo { baz = "foo text" }
    bar = Bar { baz = "bar text" }
    
    main = do
      putStrLn $ "Foo: " ++ baz (foo :: Foo) -- Foo: foo text
      putStrLn $ "Bar: " ++ baz (bar :: Bar) -- Bar: bar text
    

提交回复
热议问题