了解 elm 中的代码片段(类型更新)



下面的代码是什么意思?

type Update
    = First Field.Content
    | Last Field.Content
    | Email Field.Content
    | Remail Field.Content
    | Submit

(代码取自第 36 行 http://elm-lang.org/edit/examples/Intermediate/Form.elm)

声明一个新的类型 Update ? 这些垂直条是什么意思?

是的,这声明了一个新的类型Update。竖线可以读作"或"。也就是说,Update 类型的内容可以是:

  1. 一个First,其中包含一些数据类型为 Field.Content
  2. 的数据
  3. 一个Last,其中包含一些数据类型为 Field.Content
  4. 的数据
  5. 一个Email,其中包含一些数据类型为 Field.Content
  6. 的数据
  7. 一个Remail,其中包含一些数据类型为 Field.Content
  8. 的数据
  9. 没有相应数据的Submit

要处理类型 Update 的值,可以使用 case - of 语法来区分不同的可能值:

update : Update -> State -> State
update upd st = case upd of
  First  content -> st -- do something in the situation that the Update is a First
  Last   content -> st -- do something in the situation that the Update is a Last
  Email  content -> st -- do something in the situation that the Update is a Email
  Remail content -> st -- do something in the situation that the Update is a Remail
  Submit -> st -- do something in the situation that the Update is a Submit

我会在 Elm 网站上添加一个文档链接,但它正在为新的 0.14 版本重写。我可能会在以后回来编辑它;)

最新更新