Skip to content

Latest commit

 

History

History
197 lines (152 loc) · 5.39 KB

treasure_matching.livemd

File metadata and controls

197 lines (152 loc) · 5.39 KB

Drills: Pattern Matching

Mix.install([
  {:jason, "~> 1.4"},
  {:kino, "~> 0.9", override: true},
  {:youtube, github: "brooklinjazz/youtube"},
  {:hidden_cell, github: "brooklinjazz/hidden_cell"}
])

Navigation

Drills: Pattern Matching

Drills help you develop familiarity and muscle memory with syntax through repeated exercises. Unlike usual problems, Drills are not intended to develop problem solving skills, they are purely for developing comfort and speed.

This set of drills is for Pattern Matching. Follow the instructions for each drill and complete them as quickly as you can.

Treasure Matching

In this exercise, you're going to use pattern matching to extract the "jewel" string from the data provided and bind it to a jewel variable. The first exercise is complete for example.

[_, _, _, jewel] = [1, 2, 3, "jewel"]
jewel

Use pattern matching to bind a jewel variable to the "jewel" string. Each cell should return the jewel variable to prove it was bound correctly.

[1, 2, 3, "jewel"]
%{key1: "value", key2: "jewel"}
%{1 => "jewel"}
%{%{key: [1, 2, 3, 4, 5, {}]} => "jewel"}
%{north: %{south: %{west: %{east: "jewel"}}}}
[2, "jewel"]
["jewel", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[1, "jewel", 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[1, 2, "jewel", 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[[], [1, [2, "jewel"]]]
"here is the jewel"
{"jewel"}
{"jewel", 1}
{1, 2, "jewel"}
["jewel"] ++ Enum.to_list(1..100)
[key: "jewel"]
[south: "jewel", east: {1, 2}]
Enum.map(1..4, fn each -> (each == 2 && "jewel") || each end)
Enum.map(1..4, &((&1 > 3 && "jewel") || &1))

Sum

Create a Sum module that uses recursion and pattern matching to sum all elements in a list. Avoid using the Enum module or a comprehension.

iex> Sum.list([1, 2, 3])
6
Example Solution
defmodule Sum do
  def list(list, sum \\ 0)
  def list([], sum), do: sum
  def list([head | tail], sum), do: list(tail, sum + head)
end
defmodule Sum do
  @moduledoc """
  iex> Sum.list([1, 2, 3])
  6
  """
end

Commit Your Progress

DockYard Academy now recommends you use the latest Release rather than forking or cloning our repository.

Run git status to ensure there are no undesirable changes. Then run the following in your command line from the curriculum folder to commit your progress.

$ git add .
$ git commit -m "finish Drills: Pattern Matching exercise"
$ git push

We're proud to offer our open-source curriculum free of charge for anyone to learn from at their own pace.

We also offer a paid course where you can learn from an instructor alongside a cohort of your peers. We will accept applications for the June-August 2023 cohort soon.

Navigation