diff options
| author | Anhgelus Morhtuuzh <william@herges.fr> | 2025-11-10 12:27:21 +0100 |
|---|---|---|
| committer | Anhgelus Morhtuuzh <william@herges.fr> | 2025-11-10 12:27:21 +0100 |
| commit | 96299cbf09bdb75e4d6c6849c9c4c3ce000a6fc5 (patch) | |
| tree | 7d5f21e6c884a2cd87c619c5d97fddb4cceb7ea8 /lib | |
| parent | 7536cdbd312dff03ab10e46929dc1b072f881d01 (diff) | |
feat(parser): supports literal decimal numbers
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/elixir_math_parser.ex | 5 | ||||
| -rw-r--r-- | lib/math/calc.ex (renamed from lib/math/Calc.ex) | 0 | ||||
| -rw-r--r-- | lib/math/conversion.ex | 18 |
3 files changed, 23 insertions, 0 deletions
diff --git a/lib/elixir_math_parser.ex b/lib/elixir_math_parser.ex index 4a96daf..286829e 100644 --- a/lib/elixir_math_parser.ex +++ b/lib/elixir_math_parser.ex @@ -4,11 +4,16 @@ defmodule ElixirMathParser do """ alias ElixirMathParser.Math.Rational alias ElixirMathParser.Math.Calc + alias ElixirMathParser.Math.Conversion defp reduce_to_value({:int, _line, value}, _state) do {:ok, Rational.new(value)} end + defp reduce_to_value({:float, _line, value}, _state) do + {:ok, to_string(value) |> Conversion.literal_float_to_rational()} + end + defp reduce_to_value({:var, line, var}, state) do if !Map.has_key?(state, var) do {:error, line, "value not found for " <> to_string(var)} diff --git a/lib/math/Calc.ex b/lib/math/calc.ex index 7dc5fcc..7dc5fcc 100644 --- a/lib/math/Calc.ex +++ b/lib/math/calc.ex diff --git a/lib/math/conversion.ex b/lib/math/conversion.ex new file mode 100644 index 0000000..65ddf8f --- /dev/null +++ b/lib/math/conversion.ex @@ -0,0 +1,18 @@ +defmodule ElixirMathParser.Math.Conversion do + alias ElixirMathParser.Math.Rational + + def literal_float_to_rational(value) do + {int, dec} = Integer.parse(value) + + String.graphemes(dec) + |> Enum.reduce(Rational.new(int), fn v, acc -> + if v != "." do + num = Rational.numerator(acc) * 10 + den = Rational.denominator(acc) * 10 + Rational.new(num + String.to_integer(v), den) + else + acc + end + end) + end +end |
