Skip to content

Instantly share code, notes, and snippets.

@mogorman
Last active April 18, 2020 01:06
Show Gist options
  • Save mogorman/cbafc5a79237987a4675a56f8faf9dad to your computer and use it in GitHub Desktop.
Save mogorman/cbafc5a79237987a4675a56f8faf9dad to your computer and use it in GitHub Desktop.
Distru rpn example
defmodule Distru.Rpn do
def rpn_string(numbers) do
String.split(numbers, " ")
end
def rpn(numbers) do
Enum.reduce(numbers, [], fn term, acc ->
case Integer.parse(term) do
:error ->
length = Enum.count(acc) - 2
{begin, [item_a, item_b]} = Enum.split(acc, length)
case term do
"/" ->
begin ++ [item_a / item_b]
"*" ->
begin ++ [item_a * item_b]
"+" ->
begin ++ [item_a + item_b]
"-" ->
begin ++ [item_a - item_b]
end
{number, ""} ->
acc ++ [number]
end
end)
|> Enum.at(0)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment