Reputation: 151
I created a new datatype:
data Human = Human [Names] Age
deriving(Eq,Show)
type Names = String
type Age = Int
And now I want to access the elements of [Names] for an object of type Human:
human1 = Human ["FirstName","LastName"] 22
Is there a simple way to do this for my example such as Names human1
?
Upvotes: 0
Views: 78
Reputation: 15045
In this case the simplest way is to define a function, which pattern-matches the Human
data type:
getNames (Human names _) = names
Otherwise, you can use Record Syntax to define fields of the record:
data Human = Human { names :: [Names], age :: Age }
Using this syntax you achieve names
and age
functions, which allow you to access the fields:
human1 = Human ["FirstName","LastName"] 22
names human1
Upvotes: 5
Reputation: 301
You can either make your own accessors
names :: Human -> [Names]
names (Human n _) = n
or use lenses, which gives you that and much more.
http://hackage.haskell.org/package/lens-tutorial-1.0.3/docs/Control-Lens-Tutorial.html
Upvotes: 4