With Elm's strong types, we must be precise when writing our business code. Precision is a good thing, but it often has the drawback of being verbose. Ad hoc tuples can save the day with clear and precise syntax!
1 min read
By Holger Ludvigsen
December 7, 2020
A typical case is when you need to check multiple values. Let's say the user has chosen a size and optional color name for their product:
type Size = Small | Large size : Size color : Maybe String
And we want to put a suitable text in their confirmation dialogue:
case size of Small -> case color of Just colorName -> "A modest " ++ colorName Nothing -> "Don't worry! We will find a color for you" Large -> case color of Just colorName -> "A big great " ++ colorName Nothing -> "Don't worry! We will find a color for you" -- Oh no, duplication!
Instead of indenting away into these nested case-expressions, a common trick is to use an ad hoc tuple combining the two values into
( size, color ). Notice how clear this make the outcomes of each case:
case ( size, color ) of ( Small, Just colorName ) -> "A modest " ++ colorName ( Large, Just colorName ) -> "A big great " ++ colorName ( _ , Nothing ) -> "Don't worry! We will find a color for you"
Or consider if this
if .. else expression for the email adress of a fictional company:
email = if (userDepartment == Technology && reportTitle == "Incident") then "firstname.lastname@example.org" else if userDepartment == Operations then "email@example.com" else if (userDepartment == Sales && reportTitle == "Big sales lead") then "firstname.lastname@example.org" else "email@example.com"
This can be more consisely expressed with
case .. of on a tuple:
email = case (userDepartment, reportTitle) of (Technology, "Critical incident") -> "firstname.lastname@example.org" (Operations, _) -> "email@example.com" (Sales, "Big sales lead") -> "firstname.lastname@example.org" _ -> "email@example.com"
Before we run off with our newly acquired hammer and see a world of nails, beware that tuples in Elm are intentionally restricted to maximum three members.
The reasoning is that if you combine more values than this, you are probably better off with a proper data structure like a record where the fields are named. This is a strong restriction, but all the good kids will get the gift of clean readable code.