Practice Matching a List
You learn by doing. Here are a few exercises to play with in IEx. The solutions are here but hidden. Find the solution yourself first. Experiment. Have fun!
Exercise #1
Write the left hand side of this statement. Your goal is to bind the head of the list to a variable named head
and the rest of the list to a variable named tail
. What does the left side look like?
_your_statement = [1, 2, 3]
Exercise #2
Create a match that only matches when a list has a single item.
_your_statement = [10]
Your solution should not match with values on the right like these: [10, 20]
and [11, 12, 13]
.
Why would we want to only match in very limited cases? We don’t want to have the “greediest” match or a match that catches the most it can, we want the most specific match that meets our requirement. Pattern matching lets us more explicitly and perfectly match what we are looking for.
Exercise #3
Create a match that only matches when a list has at least two items.
Create a match that matches and pulls the first 2 items off the list and ignores the rest. Bind the first 2 elements to variables named a
and b
.
_your_statement = [1, 2]
Does your solution work with a list like [1, 2, 3]
?
Comments are closed on this static version of the site.
Comments are closed
This is a static version of the site. Comments are not available.