假设我有一个类型为elm(0.18),如下所示:
type alias CatSimple =
{ color : String
, age : Int
, name : String
, breed : String
}
Run Code Online (Sandbox Code Playgroud)
我的项目要求我也有一个类型,其中包含前一个字段的所有字段,但还有一些其他字段:
type alias CatComplex =
{ color : String
, age : Int
, name : String
, breed : String
, feral : Bool
, spayed : Bool
}
Run Code Online (Sandbox Code Playgroud)
现在让我们说我需要添加另一个字段CatSimple.我必须记得将其添加到其中CatComplex.
我希望能够动态扩充我的类型,以便我可以避免更新所有类型,或不得不求助于这样的事情:
type alias CatComplex =
{ simpleData: CatSimple
, feral : Bool
, spayed : Bool
}
Run Code Online (Sandbox Code Playgroud)
在榆树有没有办法做到这一点?
如果没有,Haskell是否提供了这样做的方法?
您可以在Elm中使用可扩展记录来定义基本类型的字段组合:
type alias Cat c =
{ c
| color : String
, age : Int
, name : String
, breed : String
}
type alias FeralCat =
Cat
{ feral : Bool
, spayed : Bool
}
Run Code Online (Sandbox Code Playgroud)
以下是如何使用它的示例:
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
}
Run Code Online (Sandbox Code Playgroud)