I have a custom data type in Haskell. I have a custom type from which I later want to get a property and output it. In Java I would just go through the properties with the . (dot) operator, however this doesn't work in Haskell. How would I go about doing this?
This is the code I have now
data Person = P Name Address
type Name = String
type Address = String
x :: Person
x = (P "abc" "def")
y :: Name
y = x.Name
main :: IO ()
main = putStrLn $ "The name is: " y
CodePudding user response:
You can use pattern matching:
y = case x of P name _ -> name
y = name where P name _ = x
y = let P name _ = x in name
You could write a field accessor function:
name (P n _) = n
y = name x
The suggestion in the comments of y = (\(P name _) -> name) x
is doing essentially this; the definition of name
above is syntax sugar for
name = \(P n _) -> n
which gives the solution from the comment once its definition is inlined.
Or you could redefine your type with record syntax and have the compiler write your accessor:
data Person = P
{ name :: Name
, address :: Address
}
y = name x
Actually, if you do this, I think I'd probably omit the type aliases.
data Person = P
{ name :: String
, address :: String
}
They are just repeating information already available in the field name, and not actually buying you much; for example, the compiler won't prevent you from accidentally reading a name from one person and storing it in the address of another.