How to access newtype named tuples fields in haskell

I declare the following newtypes types:

newtype Code = Code String deriving (Show)
newtype Name = Name String deriving (Show)
newtype Account = Account (Code, Name) deriving (Show)

So:

*Main Lib> :t Code
Code :: String -> Code
*Main Lib> :t Name
Name :: String -> Name
*Main Lib> :t Account
Account :: (Code, Name) -> Account

and then create some instances:

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")

Now I need to access, for example, only the field Codefrom the variable an, something like an.CodeHow can I do this?

Is it better to use Datainstead newtype? If Haskell allows me to create a newtype named tuple, then I assume that there should be an easy way to access the elements inside.

+4
source share
2 answers

Is it better to use datainstead newtype?

Um, ... 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 unrapper:

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 ", :

{-# 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"
+8

. .

case an of
  Account (Code c, Name n) -> "Code " ++ c ++ ", Name " ++ n

,

foo :: Account -> String
foo  (Account (Code c, Name n)) = "Code " ++ c ++ ", Name " ++ n

data .

data Account = Account Code Name
-- ...
case an of
  Account (Code c) (Name n) -> "Code " ++ c ++ ", Name " ++ n
+4

Source: https://habr.com/ru/post/1685105/


All Articles