Pattern Matching a Function Body: Lists
Pattern matching a list with function clauses is the foundation of recursively processing a list of data. We aren’t going to go into recursion here, but instead focus on getting comfortable with the different ways we can Pattern Match a list with function clauses.
Contents
Practice Exercises
The following exercises continue using the Pattern Matching project. We will continue focusing on making a single test pass at a time.
The tests we are focusing on are in test/lists_test.exs
. Running the following command will execute all the tests in this file. Running all the tests now will show they all fail.
$ mix test test/lists_test.exs
[...]
Finished in 0.1 seconds
7 tests, 7 failures
Randomized with seed 423605
Exercise #1 – Lists.is_empty?/1
In Elixir, a function can have the question mark character ?
as part of the name. By convention, this is used to convey that it returns a boolean result. This function works this way as well. If given an empty list, true
is returned. For anything else it returns false
.
mix test test/lists_test.exs:25
Exercise #2 – Lists.has_1_item?/1
This function also returns a boolean result because of the ?
in the name. If given a list with exactly 1 item, return true
. For anything else it returns false
.
mix test test/lists_test.exs:35
Exercise #3 – Lists.at_least_one?/1
This function also returns a boolean result because of the ?
in the name. If the list is not empty, return true
. For anything else it returns false
.
mix test test/lists_test.exs:40
Exercise #4 – Lists.return_first_item/1
If the list is not empty, return the first item. If the list is empty, return the atom :error
.
mix test test/lists_test.exs:50
Exercise #5 – Lists.starts_with_1?/1
If the list starts with a value of 1
, then return true
. Any other initial value returns false
.
mix test test/lists_test.exs:60
Exercise #6 – Lists.sum_pair/1
If the list has exactly two items, add them together and return the result. If the list doesn’t have exactly two items, return the atom :error
.
mix test test/lists_test.exs:70
Exercise #7 – Lists.sum_first_2/1
Given a non-empty list, take the first two elements from it, sum them together and make the summed value be the new head of the list. If the list doesn’t have at least two items in it, return the original passed in value.
mix test test/lists_test.exs:80
8 Comments
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.