Elixir程序,这个程序是做什么的?

Elixir program, what does this program do?

这是即将到来的考试的练习题之一,我不知道应该为 init() 编写什么以便输出到 运行。 如果有人能帮助我,那就太棒了

输出:这就是我想要的运行

p1=Pawn.new(),
Obj.call(p1,{:goto, 1, 2}),
1=Obj.call(p1, :x),
2=Obj.call(p1, :y),
Obj.call(p1,{:moveDelta , 3, 1}),
4=Obj.call(p1, :x ) ,
3=Obj.call(p1 ,:y ).  

在下面添加必要的代码以支持上面用于对象 pawn 的 API:

函数:这里需要填写init()函数

defmodule Obj do

def call(obj,msg) do
send obj,{self(), msg}

receive do
Response -> Response
end
   end
      end

defmodule Pawn do
def new(), do: spawn(__MODULE__,:init, [] ).
def init() do: // fill this out

感谢您的宝贵时间

我舍不得给你做所有的功课。但是,鉴于您获得的代码不是有效的 Elixir,我将为您提供部分解决方案。我已经实现了 :goto:x 处理程序。您应该能够弄清楚如何编写 :moveDelta:y 处理程序。

defmodule Obj do
  def call(obj, msg) do
    send obj, { self(), msg }

    receive do
      response -> response
    end
  end
end

defmodule Pawn do
  def new(), do: spawn(__MODULE__,:init, [] )
  def init(), do: loop({0,0})
  def loop({x, y} = state) do
    receive do
      {pid, {:goto, new_x, new_y}} -> 
        send pid, {new_x, new_y}
        {new_x, new_y}
      {pid, {:moveDelta, dx, dy}} -> 
        state = {x + dx, y + dy}
        send pid, state
        state
      {pid, :x} -> 
        send pid, x
        state
      {pid, :y} -> 
        send pid, y
        state
    end
    |> loop
  end
end

p1=Pawn.new()
Obj.call(p1,{:goto, 1, 2})
1=Obj.call(p1, :x)
2=Obj.call(p1, :y)
Obj.call(p1,{:moveDelta , 3, 1})
4=Obj.call(p1, :x ) 
3=Obj.call(p1 ,:y ) 

代码运行。这是您提供的测试用例的输出(在我修复语法问题后:

iex(5)> p1=Pawn.new()
#PID<0.350.0>
iex(6)> Obj.call(p1,{:goto, 1, 2})
{1, 2}
iex(7)> 1=Obj.call(p1, :x)
1
iex(8)> 2=Obj.call(p1, :y)
2
iex(9)> Obj.call(p1,{:moveDelta , 3, 1})
{4, 3}
iex(10)> 4=Obj.call(p1, :x )
4
iex(11)> 3=Obj.call(p1 ,:y )
3
iex(12)>

此外,我修复了给定问题中的语法问题。