Chapter 9
Tips ⚠️️
- Use try.purescript.org to test out the code examples in this book.
- Whenever the example code starts with
module Main where
, make sure to clear out the code editor on try.purescript.org before pasting new code in. This will help to avoid unncessary errors
Pattern Matching
As you can see from above, the more values our type has, the more cases we have to deal with! What if we have a type with 10 different cases, and we only want to do something different for one of them? For example, maybe we have a guessing game, where the correct answer returns a "You got it!", but all the wrong answers return a "Sorry, better luck next time!". How do we handle such a scenario?
You might be tempted to try the following:
module Main where
import Prelude
data Food
= Donuts
| Brownies
| Pizza
| Chicken
| GummyBears
| Bread
| ChocolateCake
| Speghetti
| Sandwich
| CheeseBurger
whatsMyFavoriteFood :: Food -> String
whatsMyFavoriteFood food = case food of
Speghetti -> "You got it!"
The problem with the above (and you'll see the error for this as well), is that case
statements
require every value for your type to be accounted for; you can't ignore some cases unless you're
willing to do some ugly things in your program (which we won't go over here). Also, without
accommodating the other scenarios, we couldn't return back our "Sorry, better luck next time!"
message.
So then the next thing you might think is "Ok, guess I gotta bite the bullet", and do the following:
module Main where
import Prelude
data Food
= Donuts
| Brownies
| Pizza
| Chicken
| GummyBears
| Bread
| ChocolateCake
| Speghetti
| Sandwich
| CheeseBurger
whatsMyFavoriteFood :: Food -> String
whatsMyFavoriteFood food = case food of
Speghetti -> "You got it!"
Donuts -> wrongAnswer
Brownies -> wrongAnswer
Chicken -> wrongAnswer
GummyBears -> wrongAnswer
Bread -> wrongAnswer
ChocolateCake -> wrongAnswer
Speghetti -> wrongAnswer
Sandwich -> wrongAnswer
CheeseBurger -> wrongAnswer
where
wrongAnswer :: String
wrongAnswer = "Sorry, better luck next time!"
That's just no fun at all! We don't want to have to go over every single case, that's gonna cause us a big headache. Luckily, there's a better way.
module Main where
import Prelude
data Food
= Donuts
| Brownies
| Pizza
| Chicken
| GummyBears
| Bread
| ChocolateCake
| Speghetti
| Sandwich
| CheeseBurger
whatsMyFavoriteFood :: Food -> String
whatsMyFavoriteFood food = case food of
Speghetti -> "You got it!"
otherAnswers -> "Sorry, better luck next time!"
Ah, beautiful! We just used a "catch-all" to accommodate all the other scenarios in one go! How does that work?