[英]Accessing members of a custom data type in Haskell
假设我在 Haskell 中有以下自定义数据类型和函数:
data Person = Person { first_name :: String,
last_name :: String,
age :: Int
} deriving (Eq, Ord, Show)
如果我想创建一个函数print_age
来打印一个人的年龄,像这样: print_age (Person "John" "Smith" 21)
,我将如何编写print_age
来访问年龄参数? 我是一个面向对象的人,所以我不在这里。 我基本上是在寻找相当于 Person.age 的东西。
函数 application 是前缀,所以age person
将对应于 OOP 语言中常见的person.age()
。 print_age
函数可以通过函数组合来定义 pointfree
print_age = print . age
或点满
print_age person = print (age person)
这称为记录语法, LYAH 有一个很好的部分。
当使用记录定义数据类型时,Haskell 会自动定义与记录同名的函数作为访问器,因此在这种情况下age
是年龄字段的访问器(它的类型为Person -> Int
),对于first_name
也类似和last_name
。
这些是正常的 Haskell 函数,因此被称为age person
或first_name person
。
除了其他答案中提到的age
函数外,有时使用模式匹配也很方便。
print_age Person { age = a } = {- the a variable contains the person's age -}
有一个非常无害的扩展,可以让你跳过命名位:
{-# LANGUAGE NamedFieldPuns #-}
print_age Person { age } = {- the age variable contains the person's age -}
...还有另一个,被各种社区成员以不同程度的不信任看待,这使您甚至可以跳过说您想要将哪些领域纳入范围:
{-# LANGUAGE RecordWildCards #-}
print_age Person { .. } = {- first_name, last_name, and age are all defined -}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.