繁体   English   中英

访问Haskell中的自定义类型变量的元素?

[英]Accessing elements of custom type variables in Haskell?

我有一种叫做动物的类型,其中包括动物的家庭和颜色。

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- Record -> Member类型的getter,并且它们不会修改结构

3在其他语言中,您可以考虑为类实现“ ToString”接口。 这太简单了,但足以理解此示例。

要测试代数数据类型的情况,您应该使用模式匹配而不是if语句或警卫:

case myFamily of
  Ape -> "This is an ape"
  Bear -> "Dangerous carnivore!"
  Bird -> "This can fly"
  -- and so on...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM