From 7ddc83f098cfd316656c28dcca5375b939fd6c00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?William=20Herg=C3=A8s?= Date: Sun, 9 Nov 2025 13:36:02 +0100 Subject: feat(calc)): partial supports of exp --- lib/elixir_math_parser.ex | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'lib') 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})) -- cgit v1.2.3