aboutsummaryrefslogtreecommitdiff
path: root/lib/elixir_math_parser.ex
diff options
context:
space:
mode:
authorWilliam Hergès <william@herges.fr>2025-11-09 13:36:02 +0100
committerWilliam Hergès <william@herges.fr>2025-11-09 13:36:02 +0100
commit7ddc83f098cfd316656c28dcca5375b939fd6c00 (patch)
treeca37624e84a771c8e49d8ae4623e298a9a2b9692 /lib/elixir_math_parser.ex
parent3b0cc79dee76244da55d2326cc4244a384d85e44 (diff)
feat(calc)): partial supports of exp
Diffstat (limited to 'lib/elixir_math_parser.ex')
-rw-r--r--lib/elixir_math_parser.ex23
1 files changed, 23 insertions, 0 deletions
diff --git a/lib/elixir_math_parser.ex b/lib/elixir_math_parser.ex
index 863ecd8..b5e99bd 100644
--- a/lib/elixir_math_parser.ex
+++ b/lib/elixir_math_parser.ex
@@ -57,9 +57,32 @@ defmodule ElixirMathParser do
end
end
+ defp reduce_to_value({:exp_op, lhs, rhs}, state) do
+ with {:ok, op1} <- reduce_to_value(lhs, state),
+ {:ok, op2} <- reduce_to_value(rhs, state) do
+ if Ratio.denominator(op2) == 1 do
+ {:ok, expo(op1, Ratio.numerator(op2), 1)}
+ else
+ {:error, "unsupported operation"}
+ end
+ end
+ end
+
+ #  Functions for maths
+
defp factor(n, acc) when n > 0, do: factor(n - 1, acc * n)
defp factor(0, acc), do: acc
+ defp expo(value, exponent, acc) when exponent != 0 do
+ if exponent > 0 do
+ expo(value, exponent - 1, acc * value)
+ else
+ expo(value, exponent + 1, acc / value)
+ end
+ end
+
+ defp expo(_value, 0, acc), do: acc
+
defp evaluate_tree([{:assign, {:var, line, lhs}, rhs} | tail], state) do
with {:ok, val} <- reduce_to_value(rhs, state) do
evaluate_tree(tail, Map.merge(state, %{lhs => val}))