Elm语言中case表达式|运算符作用及记录更新语法解析
| Operator in Elm: Two Distinct Uses Great questions! Let’s break down the two separate roles of the | symbol in your Elm code—they look the same but serve completely different purposes.
1. | in Case Expressions: Pattern Matching Branch Separator
In Elm’s case expression, the | acts as a separator for pattern-matching branches. It lets you list all possible patterns your value could match, each paired with the code to execute when that pattern is hit.
In your snippet:
case msg of Change newContent -> { model | content = newContent }
If you had more Msg variants (like a Submit action), you’d add another branch with |:
case msg of Change newContent -> { model | content = newContent } Submit -> { model | content = "Submitted!" }
Each | signals "here’s another possible pattern to check against the value (msg in this case)". Elm evaluates branches in order, runs the code for the first matching pattern, and stops.
2. { model | content = newContent }: Immutable Record Update Syntax
This is Elm’s record update syntax—and despite sharing the | symbol, it has no connection to the case expression’s use of the character.
Here’s exactly what this line does:
- It creates a new copy of the
modelrecord (Elm is purely functional, so all data is immutable—you can’t modify the originalmodeldirectly). - It preserves all existing fields of
modelexactly as they are. - It only overwrites the
contentfield with the value ofnewContent.
To address your specific follow-ups:
- It does not bind
newContentto bothmodelandcontent. The originalmodelstays unchanged; this syntax generates a brand-newModelinstance with an updatedcontentfield. - The
|here is just part of the record update syntax—it separates the original record (model) from the list of fields you want to update. It’s purely a syntax choice, unrelated to thecasebranch separator.
For example, if your Model had extra fields like id : Int, this syntax would keep the id intact while updating content:
type alias Model = { id : Int, content : String } -- Creates new record with same id, updated content { model | content = newContent }
内容的提问来源于stack exchange,提问作者Saurabh kukade




