[英]Augmenting type aliases in elm or haskell
Say I have a type in elm (0.18) like this: 假设我有一个类型为elm(0.18),如下所示:
type alias CatSimple =
{ color : String
, age : Int
, name : String
, breed : String
}
My project requires that I also have a type that has all the fields of the previous one, but with a few additional fields: 我的项目要求我也有一个类型,其中包含前一个字段的所有字段,但还有一些其他字段:
type alias CatComplex =
{ color : String
, age : Int
, name : String
, breed : String
, feral : Bool
, spayed : Bool
}
Now let's say that I need to add another field to CatSimple
. 现在让我们说我需要向CatSimple
添加另一个字段。 I would have to remember to add it to CatComplex
as well. 我必须记得将它添加到CatComplex
中。
I would like to be able to dynamically augment my types so that I can avoid having to update all of them, or having to resort to something like this: 我希望能够动态扩充我的类型,以便我可以避免更新所有类型,或不得不求助于这样的事情:
type alias CatComplex =
{ simpleData: CatSimple
, feral : Bool
, spayed : Bool
}
Is there any way to do that in Elm? 在榆树有没有办法做到这一点?
If not, does Haskell provide a way to do this? 如果没有,Haskell是否提供了这样做的方法?
You can use extensible records in Elm to define a rudimentary sort of field composition: 您可以在Elm中使用可扩展记录来定义基本类型的字段组合:
type alias Cat c =
{ c
| color : String
, age : Int
, name : String
, breed : String
}
type alias FeralCat =
Cat
{ feral : Bool
, spayed : Bool
}
Here's an example of how it could be used: 以下是如何使用它的示例:
feralCatSummary : FeralCat -> String
feralCatSummary { color, feral } =
color ++ "; Feral? " ++ toString feral
main : Html msg
main =
text <|
feralCatSummary
{ color = "Blue"
, age = 5
, name = "Billy"
, breed = "Bluecat"
, feral = True
, spayed = False
}
The short answer is no, but there are some things you can do that go in the direction you want: 简短的回答是否定的,但是你可以做一些你想要的方向:
Have a single type but make the extra info 'optional' 有一种类型,但额外的信息'可选'
type alias Cat =
{ color : String
, age : Int
, name : String
, breed : String
, feral : Maybe Bool
, spayed : Maybe Bool
}
When you want to pass CatComplex to a function that only uses the Cat fields you could define a Type 如果要将CatComplex传递给仅使用Cat字段的函数,可以定义类型
type alias CatGeneric a =
{ a|
color : String
, age : Int
, name : String
, breed : String
}
then 然后
fn : CatGeneric a -> Bool
....
and this should type check if you pass either a Cat or a CatComplex 如果你通过Cat或CatComplex,这应该输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.