What is the correct way to perform object overloading in Elixir? I am trying to currently overload the <
operator, however, I keep getting an error.
Basically, I have the following object oriented Python code:
class Value:
def __init__(self, a, b):
self.a = a
self.b = b
def __lt__(self, other):
return self.f1() > other.f1()
def f1(self):
return (self.a * self.b)
def get_value(self, obj2):
if self.f1() < obj2.f1():
print("Done")
else:
print("Not Done")
v1 = Value(1, 3)
v2 = Value(2, 4)
v1.get_value(v2)
Now, my way of converting this in Elixir is the following:
defmodule Value do
import Kernel, except: [<: 2]
defstruct a: 0, b: 0
def init(a, b), do: %Value{a: a, b: b}
def v < other do
v.a > other.a and v.b > other.b
end
def f1(v) do
(v.a * v.b)
end
def get_value(obj1, obj2) do
if f1(obj1) < f1(obj2), do: IO.puts "Done", else: IO.puts "Not Done"
end
end
v1 = Value.init(1, 3)
v2 = Value.init(2, 4)
Value.get_value(v1, v2)
This, however, gives me the following error:
** (ArgumentError) you attempted to apply :a on 3. If you are using apply/3, make sure the module is an atom. If you are using the dot syntax, such as map.field or module.function, make sure the left side of the dot is an atom or a map
:erlang.apply(3, :a, [])
jdoodle.exs:9: Value.</2
jdoodle.exs:17: Value.get_value/2
Can someone guide me as to what is wrong in my implementation and technically, whats the correct way to overload the <
operator in Elixir?