如何从给定数据类型的列表中提取字段列表? [英] How to extract a list of fields from a list of a given data type?

查看:146
本文介绍了如何从给定数据类型的列表中提取字段列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我已经定义了一个数据类型,比方说5个属性。我如何能够创建一个属性列表。

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.

例如:

data Person = Person name fname sexe age height

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

我可以返回一个包含所有名称的列表:( Marie John Jessie code>)

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

推荐答案

您的代码不是有效的Haskell。你可以有

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

然后你可以创建一个包含三个值 marie john 的列表,和 jessie with

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

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

现在您可以使用许多内置函数如 map 过滤器

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

现在,如果您将此加载到GHCi中可以测试它为

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

> ages db
[25, 26, 27]

有些事情要注意:


  • 所有数据类型必须声明,如果它们不是内置的。

  • 用<$声明新类型c $ c> data TypeName = ConstructorName< FieldTypes>

  • 声明别名类型AliasName = ExistingType

  • 类型名称和构造函数必须以大写字母开头

  • 值名称必须以小写字母开头

  • 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.

这篇关于如何从给定数据类型的列表中提取字段列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆