简体   繁体   English

Elixir,该程序在做什么?

[英]Elixir, what is this program doing?

I have been given this code by our teacher. 我们的老师给了我这个代码。 I am having trouble following what this code does. 我在遵循此代码的作用时遇到了麻烦。 This is all I know so far: [x1, y1 | z1] = Output2.abc(3) 到目前为止,这就是我所知道的: [x1, y1 | z1] = Output2.abc(3) [x1, y1 | z1] = Output2.abc(3) is called, and so function abc(2) will spawn a new process assigned as y . [x1, y1 | z1] = Output2.abc(3) ,因此函数abc(2)将产生一个分配为y的新进程。 Then it will send the value 2 to y . 然后它将值2发送到y When it receives 2, I am stuck at what receive is doing. 当接收到2时,我会陷入接收正在做的事情。 What does z -> z mean? z -> z是什么意思?

Also, the prof asks what `x1, y1 are. 另外,教授询问`x1,y1是什么。 I don't understand where these variables are located in this code. 我不明白这些变量在此代码中的位置。 If someone can just guide me through this it would be much appreciated. 如果有人可以指导我完成此工作,将不胜感激。 Thanks 谢谢

defmodule Output2 do
  def abc(x) do
    y = spawn_link(__MODULE__, :n, [self()])
    send y, x
    receive do
      z -> z
    end
  end

  def n(z) do
    receive do
      v -> send z, n(v * v, v)
    end
  end

  defp n(x, x), do: [x]
  defp n(x, y), do: [y | n(x, y + y)]
end

[x1, y1 | z1] = Output2.abc(2)
  1. Output2.abc(2) is called. Output2.abc(2)
  2. A linked process is started with spawn_link/3 using n(z) as the receiver 使用n(z)作为接收者,以spawn_link / 3开始一个链接过程
    1. The original process waits for a message from the recently spawned process. 原始进程等待来自最近生成的进程的消息。
  3. The parameter x (ie 2) is sent to the process started in #2 参数x(即2)被发送到#2中开始的进程
  4. The process started in #2 sends back the result of n(v * v, v) 从#2开始的过程发回n(v * v, v)
    1. n(v * v, v) is a call to n(x, y) because x, and y are different values. n(v * v, v)是对n(x, y)的调用n(x, y)因为x和y是不同的值。
    2. So, we have n(2*2, 2) . 因此,我们有n(2*2, 2) n(x,y) returns a list of y concatenated with n(x, y+y) where x = 4, and y = 2 n(x,y)返回与n(x, y+y)串联的y列表,其中x = 4,y = 2
    3. From the previous step n(4, 2+2) is called, which invokes n(x, x) returning a single item list of [4] 从上一步中调用n(4, 2+2) ,调用n(x, x)返回单个项目列表[4]
    4. From 4.2, [2 | 从4.2,[2 | [4]] results in [2 | [4]]产生[2 | 4] (a list of two elements: 2, 4) 4](两个元素的列表:2、4)
  5. The original process received the list as z , and returns z ( z -> z ) 原始进程将列表作为z接收,并返回zz -> z
  6. Pattern matching is used to assign x1 = 2, and y1 = 4. z1 is the tail of the rest, which is empty. 模式匹配用于分配x1 = 2,y1 =4。z1是其余部分的尾部,为空。

z -> z就像函数定义: fun(z) {return z}并且z是从接收函数获得的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM