Elixir
  • My Elixir journey
  • Why functional programming?
  • Exhort
    • 🗓️Day 22
    • 🗓️Day 21
    • 🗓️Day 20
    • 🗓️Day 19
    • 🗓️Day 18
    • 🗓️Day 17
    • 🗓️Day 16
    • 🗓️Day 15
    • 🗓️Day 14
  • Bits and pieces
    • Clean mix dependencies
    • Run tests automatically on save
    • Run tests and stop on first failure
    • How to remove Tailwind from a Phoenix project
Powered by GitBook
On this page
  • Exercises
  • RPN Calculator
  • Overall progress
  1. Exhort

Day 20

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

PreviousDay 21NextDay 19

Last updated 2 years ago

Exercises

RPN Calculator

|

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

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

🗓️
Exercise on Exercism
View my solution
View gist on GitHub
RPN Calculator
Progress
An image showing my progress on Exercism. It's 21.8% as of Saturday, 27 August 2022.