Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get the named fields in haskell correctly?

I am writing a parser with the help of parsec and I have a problem

data Param = Param {paramName::String, argument :: Maybe String}
  deriving (Show)

paramExpr1 :: Parser Param
paramExpr1 = do
  paramKeyword
  void $ lexeme $ char '-'
  paramName <- word
  return $ Param paramName Nothing 

paramExpr3 :: Parser Param
paramExpr3 = do
  pN  <- paramExpr1 -- <- PROBLEM HERE
  return $ Param pN Nothing 

In short, I don’t understand how to get the named field, paramExpr1 will return Param and I would like to get paramName, but I don’t understand how

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can extract the field by using the field name as a function:

paramExpr3 :: Parser Param
paramExpr3 = do
  pN <- paramExpr1
  return $ Param (paramName pN) Nothing 

Alternatively, instead of creating a new value using the constructor Param, you can use the record update syntax and change the fields you want to change while leaving the others as they are.

paramExpr3 :: Parser Param
paramExpr3 = do
  pN <- paramExpr1
  return pN{ argument = Nothing }

More alternatives exist (e.g. using lenses), but these are the most basic approaches.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading