Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Replacing Nils

drill-patternmatching-replace-nils.livemd

Replacing Nils

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

Navigation

Home Report An Issue Drills: Pattern MatchingMetric Conversion

Replacing Nils

This exercise was inspired by Quentin Crain, one of our amazing DockYard Academy mentors.

Given two lists of the same length, replace nil values in the first list with non-nil values in the second list.

list1 = [1, 2, 3, nil, 5]
list2 = ["1", "2", "3", "4", "5"]

[1, 2, 3, "4", 5] = Replace.nils(list1, list2)

Example Solution

defmodule Replace do
  def nils(list1, list2) do
    Enum.zip(list1, list2)
    |> Enum.map(fn
      {nil, value} -> value
      {value, _} -> value
    end)
  end
end
defmodule Replace do
  @doc """
  iex> Replace.nils([1, 2, 3, nil, 5], ["1", "2", "3", "4", "5"])
  [1, 2, 3, "4", 5]

  iex> Replace.nils([nil, nil, nil, nil, "5"], [1, 2, 3, 4, 5])
  [1, 2, 3, 4, "5"]
  """
  def nils(list1, list2) do
  end
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 Replacing Nils 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

Home Report An Issue Drills: Pattern MatchingMetric Conversion