下面的代码是什么意思?
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
类型的内容可以是:
- 一个
First
,其中包含一些数据类型为Field.Content
的数据 - 一个
Last
,其中包含一些数据类型为Field.Content
的数据 - 一个
Email
,其中包含一些数据类型为Field.Content
的数据 - 一个
Remail
,其中包含一些数据类型为Field.Content
的数据 - 或没有相应数据的
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 版本重写。我可能会在以后回来编辑它;)