How to extract a list of fields from a list of a given data type?

删除回忆录丶 提交于 2020-01-17 13:26:29

问题


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)


回答1:


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.



回答2:


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.



来源:https://stackoverflow.com/questions/35966088/how-to-extract-a-list-of-fields-from-a-list-of-a-given-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!