在 Haskell 中访问自定义数据类型的成员 [英] Accessing members of a custom data type in Haskell
问题描述
假设我在 Haskell 中有以下自定义数据类型和函数:
Say I have the following custom data type and function in 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 的东西.
If I want to create a function print_age
to print a Person's age, like so: print_age (Person "John" "Smith" 21)
, how would I write print_age
to access the age parameter? I'm an Object Oriented guy, so I'm out of my element here. I'm basically looking for the equivalent of Person.age.
推荐答案
Function application 是前缀,所以 age person
将对应于常见的 person.age()
面向对象语言.print_age
函数可以通过函数组合来定义pointfree
Function application is prefix, so age person
would correspond to the person.age()
common in OOP languages. The print_age
function could be defined pointfree by function composition
print_age = print . age
或点满
print_age person = print (age person)
这篇关于在 Haskell 中访问自定义数据类型的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!