i learning programming language elm. want access particular field of union. unable access it. have searched in documentation. not find anywhere how access particular field of union. code follows:
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 unions fields people : list person people = [ p1 , p2 , person {fname= "anakin", lname= "luke", age= 12} ] main = show [people] i cannot use p1.name since p1 not record. how access field fname of p1 or p2?
the documentation on website still getting improved, , need more links between different parts. documentation you're looking here.
case expressions
the relevant part explains union type can have different tagged values, need case-expression distinguish different options:
case p1 of person r -> r.fname let expressions
since in case there 1 option, can safely use deconstruction pattern in variable assignment:
(person p1record) = p1 -- p1record defined, , can use p1record.fname be careful let expressions
note if use assignment trick union type multiple tags, open program runtime crashes. crash happen if value try deconstruct not of right tag:
type direction = left | right | forward | march : direction -> boolean march dir = let forward = dir -- contrived example in true main = show (march back) -- oops, runtime crash final note
since union type has 1 tag, may want consider using type alias instead. it's utility write nicer name type, don't have unwrap use inner type:
type alias person = {fname: string, lname: string, age: int} p1 = {fname= "abc", lname= "xyz", age= 23} -- p1.fname accessible
Comments
Post a Comment