Not an ID
Not an ID

Reputation: 2589

Understanding a code snippet in elm (type Update)

What's the following code mean?

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

(code taken from http://elm-lang.org/edit/examples/Intermediate/Form.elm line 36)

declare a new type Update? what does those vertical bars mean?

Upvotes: 2

Views: 132

Answers (1)

Apanatshka
Apanatshka

Reputation: 5958

Yes this declares a new type Update. The vertical bars can be read as "or". That is, something of type Update can be either:

  1. a First, which has some data in it of type Field.Content
  2. a Last, which has some data in it of type Field.Content
  3. an Email, which has some data in it of type Field.Content
  4. a Remail, which has some data in it of type Field.Content
  5. or a Submit, which has no corresponding data.

To handle a value of type Update, you can use the case-of syntax to distinguish the different possible values:

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

I would add a link to the documentation on the Elm website, but it's in the middle of a rewrite for the new 0.14 release. I may come back and edit it in later ;)

Upvotes: 1

Related Questions