Should this code be using pattern matching?

Hi, should I be using pattern matching in the code below? If so, how would you refactor it to use pattern matching ?


defmodule App do
  def random_number do
   #Hard coded
    40
  end

  def user_guess(guess) do
    cond do
      guess == random_number ->
        IO.inspect("YOU WIN")

      guess > random_number ->
        IO.inspect("LOWER")

      guess < random_number ->
        IO.inspect("HIGHER")
    end
  end
end

No, not pattern match, guard clause in that case…

https://hexdocs.pm/elixir/1.10.3/Kernel.html#module-guards

But You cannot use random_number inside the guard. You could as well define a module attribute.

def user_guess(guess) when guess == 40, do: IO.inspect("YOU WIN")

etc
2 Likes