我声明以下新类型:
newtype Code = Code String deriving (Show)
newtype Name = Name String deriving (Show)
newtype Account = Account (Code, Name) deriving (Show)
所以:
*Main Lib> :t Code
Code :: String -> Code
*Main Lib> :t Name
Name :: String -> Name
*Main Lib> :t Account
Account :: (Code, Name) -> Account
然后我创建了一些实例:
cn = Code "1.1.1"
nn = Name "Land And Buildings"
an = Account (cn, nn)
*Main Lib> an
Account (Code "1.1.1",Name "Land And Buildings")
现在我只需要访问变量
Code
中的 an
字段,比如 an.Code
我该怎么做?使用
Data
而不是 newtype
更好吗?如果 Haskell 允许我创建一个名为 tuple 的新类型,那么我想应该有一种简单的方法来访问里面的元素。
最佳答案
Is it better to use
data
instead of anewtype
?
嗯,是的......
newtype
的全部意义在于给单一类型一个新名称。它不应该用于构建复合类型。所以,就像 user2407038 建议的那样,让它data Account = Account
{ accCode :: Code
, accName :: Name
} deriving (Show)
然后你可以简单地使用
*Main Lib> let an = Account (Code "1.1.1") (Name "Land And Buildings")
*Main Lib> accCode an
Code "1.1.1"
也就是说,如果你给 newtype 一个解包器,访问埋在 newtype 中的元组中的字段也不难:
newtype Account = Account {getAccount :: (Code, Name)}
deriving (Show)
然后
*Main Lib> let an = Account (Code "1.1.1", Name "Land And Buildings")
*Main Lib> fst $ getAccount an
Code "1.1.1"
如果你想花哨,你也可以使用“20.2 世纪记录访问器”, lenses :
{-# LANGUAGE TemplateHaskell, FunctionalDependencies #-}
import Lens.Micro
import Lens.Micro.TH
data Account = Account
{ accountCode :: Code
, accountName :: Name
} deriving (Show)
makeFields ''Account
然后
*Main Lib> let an = Account (Code "1.1.1") (Name "Land And Buildings")
*Main Lib> an^.code
Code "1.1.1"
关于haskell - 如何访问haskell中的新类型命名元组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46059483/