我有一种叫做动物的类型,其中包括动物的家庭和动物的颜色。
type Animal family = [(family, color)]
data Family = Ape | Bear | Bird | Cat | Dog | Chicken
data Color = Brown | Black | White | Other
我还具有尝试访问动物的科目和颜色的功能。我要问的只是简单地如何从函数中访问这些元素。例如,在大多数面向对象的语言中,我们将使用animal.family之类的元素来访问这些元素。
animalFunction :: Animal -> String
animalFunction animal
| animal.family == Ape = "This animal is an ape."
type Animal family = [(family, color)]
首先,这不应该编译;如果更改为[(family, Color)]
这是一个类型别名,表示这Animal
意味着(参数化的家庭类型,颜色)元组1的列表,这很可能不是您想要的。
正如@rightfold所建议的,您可能想要
data Animal = Animal Family Color
或者,使用记录语法:
data Animal = Animal { family :: Family, color :: Color }
然后,您的功能:
-- record version
animalFunction :: Animal -> String
animalFunction animal
| family animal == Ape = "This animal is an ape."
| ...
笔记:
family :: Animal -> Family
或者,您可以仅将模式匹配2。
animalFunction (Animal f c)
| f == Ape = ...
甚至:
animalFunction (Animal Ape _) = ...
但是,您可能正在寻找的是Show
将某些东西转换为String
3的通用惯用方式。
data Family = Ape | Bear | Bird | Cat | Dog | Chicken deriving (Show)
instance Show Animal where
show (Animal f _) = "This animal is an " ++ (show f) ++ "."
1对。
2它同时适用于记录和非记录,因为记录只会真正Record -> Member
为每个成员引入类型的getter ,而它们不会修改结构
3在其他语言中,您可以考虑为类实现“ ToString”接口。这太简单了,但是足以理解此示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句