From 4840f480c8f255a6cf3b4eed291a00cea76b0cac Mon Sep 17 00:00:00 2001 From: Anhgelus Morhtuuzh Date: Mon, 10 Nov 2025 17:31:41 +0100 Subject: feat(calc): supports function definition and evaluation --- lib/math/function.ex | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 lib/math/function.ex (limited to 'lib/math/function.ex') diff --git a/lib/math/function.ex b/lib/math/function.ex new file mode 100644 index 0000000..2acf2c4 --- /dev/null +++ b/lib/math/function.ex @@ -0,0 +1,28 @@ +defmodule ElixirMathParser.Math.Function do + alias ElixirMathParser.Math.Function + + defstruct relation: nil, parameters: %{} + + def is_function(val) when is_map(val) and is_map_key(val, :__struct__) and is_struct(val), + do: :erlang.map_get(:__struct__, val) == __MODULE__ + + def new(relation, parameters) do + params = + Enum.with_index(parameters) + |> Enum.reduce(%{}, fn {v, id}, acc -> Map.merge(acc, %{id => v}) end) + + %Function{relation: relation, parameters: params} + end + + def eval(fun, parameters) do + if Enum.count(parameters) != Enum.count(fun.parameters) do + {:error, "wrong count of parameters"} + else + params = + Enum.with_index(parameters) + |> Enum.reduce(%{}, fn {v, id}, acc -> Map.merge(acc, %{v => id}) end) + + fun.relation.(fun.parameters, params) + end + end +end -- cgit v1.2.3