🗓️Day 22
Monday, 29 August 2022 - Day 22 of Exhort August 2022 - Exercism (My Elixir Journey)
Exercises
Stack Underflow
Exercise on Exercism | View my solution
Solution
Expand to see code (spoiler alert)
defmodule RPNCalculator.Exception do
defmodule DivisionByZeroError do
defexception message: "division by zero occurred"
end
defmodule StackUnderflowError do
defexception message: "stack underflow occurred"
@impl true
def exception(value) do
case value do
[] ->
%StackUnderflowError{}
_ ->
%StackUnderflowError{message: "stack underflow occurred, context: " <> value}
end
end
end
def divide(stack) when length(stack) < 2, do: raise(StackUnderflowError, "when dividing")
def divide([0, _nominator] = _stack), do: raise(DivisionByZeroError)
def divide([divisor, nominator]) when divisor != 0, do: nominator / divisor
end
View gist on GitHub
Notes
Overall progress