🗓️Day 20

Saturday, 27 August 2022 - Day 20 of Exhort August 2022 - Exercism (My Elixir Journey)

Exercises

RPN Calculator

Exercise on Exercism | View my solution

Solution

Expand to see code (spoiler alert)
defmodule RPNCalculator do
  @spec calculate!(list(), Function.t()) :: :ok
  def calculate!(_stack, operation) do
    operation.(1)
  end

  @spec calculate(list(), Function.t()) :: {:ok, String.t()} | :error
  def calculate(_stack, operation) do
    try do
      operation.(1)
      {:ok, "operation completed"}
    rescue
      _ -> :error
    end
  end

  @spec calculate_verbose(list(), Function.t()) :: {:ok | :error, String.t()}
  def calculate_verbose(_stack, operation) do
    try do
      operation.(1)
      {:ok, "operation completed"}
    rescue
      e in ArgumentError -> {:error, e.message}
    end
  end
end

View gist on GitHub

Notes

I was trying to figure out how to call an anonymous function assigned to a variable when the anonymous functions has no arguments. It's the_variable.(). However, it turns out this exercise expects an anonymous function with an arity of 1. But the parameter is not being used. So you can pass anything really: the_variable.(1).

Overall progress

Last updated