在别名记录中设置值

时间:2016-06-07 18:53:23

标签: elm

我刚刚开始与榆树一起,所以要好好:)

"Random" example of the official Elm Guide中,模型似乎用值1初始化,如下所示:

type alias Model =
  { dieFace : Int
  }


init : (Model, Cmd Msg)
init =
(Model 1, Cmd.none)

我对此的理解是代码

Model 1

设置记录中dieFace属性的值。这是正确的,如果是这样的话:设置记录属性的这种奇怪的语法是什么?

我想要的东西
{ model | dieFace = 1 }

1 个答案:

答案 0 :(得分:5)

Model是记录的类型别名,它具有一个名为dieFace的int值。

有几种方法可以创建该类型的值:

Model 1 -- treats Model as a function with a single parameter

{ dieFace = 1 } -- creates a record that happens to coincide with the Model alias

您在{ model | dieFace = 1 }中看到的奇怪语法是根据现有记录值创建新值但更改一个或多个字段的简写。当你的记录类型只有一个字段时,这可能没什么意义,所以让我们创建一个任意的例子:

type alias ColoredDie = { dieFace: Int, color: String }

你可以在Elm REPL中玩游戏,也许这有助于理解:

> blue3 = ColoredDie 3 "blue"
{ dieFace = 3, color = "blue" } : Repl.ColoredDie
> red3 = { blue3 | color = "red" }
{ dieFace = 3, color = "red" } : { dieFace : Int, color : String }
> red4 = { red3 | dieFace = 4 }
{ dieFace = 4, color = "red" } : { color : String, dieFace : number }
> green6 = { red4 | color = "green", dieFace = 6 }
{ dieFace = 6, color = "green" } : { color : String, dieFace : number }

你可以read up on Elm's record syntax here