How do I access the Union fields in Elm?
I am learning Elm programming language. I want to access a specific area of ββthe pool. I cannot access it. I have looked in the documentation. But I couldn't find anywhere how to access a specific area of ββthe Union. The code looks like this:
import Graphics.Element exposing (show)
import List exposing (length, filter, map)
type Person
= Person { fname: String, lname: String, age: Int}
p1 = Person { fname="ABC", lname="XYZ", age=23 }
p2 = Person { fname="JK", lname="Rowling", age=24 }
-- These are unions with fields
people : List Person
people = [ p1
, p2
, Person {fname= "Anakin", lname= "Luke", age= 12}
]
main = show [people]
I cannot use p1.name
it because p1
it is not a record. How do I access a field fname
from p1
or p2
?
source to share
The documentation on the website is still improving and requires additional links between the different parts. The documentation you are looking for is here .
Case expressions
The related part explains that a union type can have different tagged values, so you need a case-expression to distinguish between different parameters:
case p1 of
Person r -> r.fname
Let the expressions
Since there is only one option in your case, you can also safely use the deconstruction pattern in a variable assignment:
(Person p1Record) = p1
-- now p1Record is defined, and you can use p1Record.fname
Be careful if expressions
Note that if you use this assignment trick for a multi-tag merge type, you open your program before runtime crashes. It will fail if the value you are trying to deconstruct does not match the correct tag:
type Direction
= Left
| Right
| Forward
| Back
march : Direction -> Boolean
march dir =
let
Forward = dir -- contrived example
in
True
main =
show (march Back) -- oops, runtime crash
Final note
Since your union type only has one tag, you can use instead type alias
. It's just a utility for writing a better name for the type, but you don't need to expand it to use the inner type:
type alias Person
= {fname: String, lname: String, age: Int}
p1 = {fname= "ABC", lname= "XYZ", age= 23}
-- p1.fname is immediately accessible
source to share