我和我的一些同事正在设计一种新的编程语言,我们正在考虑将Elixir作为目标语言。但事实是,该语言主要基于Scala的语法和语义,这意味着它需要以某种方式允许继承。
然而,不是类,而是在他们的位置使用actor,但这引发了一个有趣的问题:如何使用Elixir函数模拟类类继承?或者换句话说,是否有可能以某种方式获得一个函数来继承另一个函数的receiver
模式?
A-la this:
def io_port do
receive do
{:transmit, data} -> # do stuff with data
{:receive, data} -> # do other stuff with data
end
end
def thunderbolt, extends: io_port do
receive do # also accepts all the same messages io_port does
{:display, data} -> # same story again
end
end
答案 0 :(得分:1)
Elixir doesn't allow You to insert macros at the matching level like:
receive do
macro1()
macro2()
end
So You can't really do dynamic matching on messages.
But You could use OTP components to make something similar to inheritance
like:
defmodule IOPort do
use Actor
defmacro receiver do
quote do
def handle_call({:transmit, data}), do: # do stuff with data
end
end
end
and
defmodule Thunderbolt do
use Actor, extend: IOPort
defmacro receiver do
quote do
def handle_call({:display, data}), do: # do stuff with data
end
end
end
And write something like
defmodule Actor
defmacro __using__([]) do
__MODULE__.receiver
end
defmacro __using__([extends: mod]) do
mod.receiver
__MODULE__.receiver
end
end
Of course it's just a concept, not really tested. But it could work like that with GenServer, plus using OTP would save You a lot of reinventing the wheel
PS. PM me about this programming language of yours. If it's worth a while I'd gladly help