2017-04-15 33 views
0

这是从即将到来的考试实践问题之一,我不知道应该的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). 

添加必要的代码如下,以支持上述的对象棋子使用的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 

谢谢您的时间

+1

你的问题是完全错误的第一块看起来更加。像二郎语法。你的第二块是没有缩进和不可读。 –

+0

我的教授很烂的家伙,但它是仙丹我向你保证。 –

回答

3

我不愿意做你的功课你。但是,鉴于您提供的代码不是有效的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)> 

而且,我在给定的问题固定的语法问题

+0

先生,非常感谢您的帮助。这真的帮助像20名学生 –

+0

你得到其他两种处理程序的工作原理?您是否使所有测试案例工作? –