在elm或haskell中增加类型别名
假设我在elm(0.18)中有这样一个类型:在elm或haskell中增加类型别名,haskell,elm,Haskell,Elm,假设我在elm(0.18)中有这样一个类型: type alias CatSimple = { color : String , age : Int , name : String , breed : String } type alias CatComplex = { simpleData: CatSimple , feral : Bool , spayed : Bool } 我的项目要求我还有一个类型,该类型包含上一个类型的所有字段,但有几个附加字段:
type alias CatSimple =
{ color : String
, age : Int
, name : String
, breed : String
}
type alias CatComplex =
{ simpleData: CatSimple
, feral : Bool
, spayed : Bool
}
我的项目要求我还有一个类型,该类型包含上一个类型的所有字段,但有几个附加字段:
type alias CatComplex =
{ color : String
, age : Int
, name : String
, breed : String
, feral : Bool
, spayed : Bool
}
现在让我们假设我需要将另一个字段添加到CatSimple
。我还必须记得将它添加到CatComplex
中
我希望能够动态地扩充我的类型,这样我就可以避免更新所有类型,或者不得不求助于以下方法:
type alias CatSimple =
{ color : String
, age : Int
, name : String
, breed : String
}
type alias CatComplex =
{ simpleData: CatSimple
, feral : Bool
, spayed : Bool
}
在Elm有没有办法做到这一点
如果没有,Haskell是否提供了这样做的方法?简短的回答是否定的,但有一些事情可以朝着你想要的方向做: 使用单一类型,但将额外信息设置为“可选”
type alias Cat =
{ color : String
, age : Int
, name : String
, breed : String
, feral : Maybe Bool
, spayed : Maybe Bool
}
当您想要将CatComplex传递给只使用Cat字段的函数时,您可以定义一个类型
type alias CatGeneric a =
{ a|
color : String
, age : Int
, name : String
, breed : String
}
然后
如果您通过了Cat或CatComplex,则应进行类型检查。您可以使用Elm中的可扩展记录来定义基本类型的字段组合:
类型别名Cat c=
{c
|颜色:字符串
,年龄:整数
,名称:String
,品种:细绳
}
类型别名FeralCat=
猫
{野性:布尔
,spayed:Bool
}
下面是一个如何使用它的示例:
FeralCat摘要:FeralCat->String
野性{颜色,野性}=
颜色++“野性?”++toString野性
主:Html消息
主要=
文本