How to extract a list of fields from a list of a g

2019-09-20 17:22发布

If I have defined a datatype with, let's say, 5 attributes. How would I be able to create a list of one of the attributes.

Ex :

data Person = Person name fname sexe age height

Marie, John, Jessie :: Person
Marie = Person "Marie" _ _ _
John = Person "John" _ _ _
Jessie = Person "Jessie" _ _ _

How can I return a list containing all the names : (Marie, John, Jessie)

2条回答
劳资没心,怎么记你
2楼-- · 2019-09-20 17:35

Your code isn't valid Haskell. You could have

data Person = Person FName LName Sexe Age Height
type FName = String
type LName = String
data Sexe = Male | Female
type Age = Int
type Height = Float

marie, john, jessie :: Person
marie = Person "Marie" "Lastname1" Female 25 165
john = Person "John" "Lastname2" Male 26 180
jessie = Person "Jessie" "Lastname3" Female 27 170

Then you could create a list containing the three values marie, john, and jessie with

db :: [Person]
db = [marie, john, jessie]

Now you can operate on this list using many built in functions like map and filter:

getAge :: Person -> Age
getAge (Person _ _ _ age _) = age

ages :: [Person] -> [Age]
ages people = map getAge people

Now if you load this into GHCi you can test this as

> ages db
[25, 26, 27]

Some things to note:

  • All data types must be declared if they aren't build in.
  • Declare new types with data TypeName = ConstructorName <FieldTypes>
  • Declare type aliases with type AliasName = ExistingType
  • Type names and constructors must start with a capital letter
  • Value names must start with a lower case letter.
查看更多
▲ chillily
3楼-- · 2019-09-20 17:57

You can map over the list with a function that extracts the name:

map (\ (Person name _ _ _ _) -> name) people

And if your data type is defined as a record, like this:

data Person = Person
  { personName, personFName, personSex :: String
  , personAge, personHeight :: Int
  }

Then you can simply say map personName people.

查看更多
登录 后发表回答