開始 Elixr! [下]

2015-07-25, Saturday
elixir erlang

在前一篇的文章介紹了一些Elixir的基礎,在本篇我想對於 Process & Message sending的部分做一個介紹。

1
2
3
4
5
6
7
8
9
#製作一個 Anonymous functions
f = fn -> 2 * 2 end
#folk process , 它將會回覆關於這個process的pid,
# 你可以透過pid對這個process send 一些資訊給它
spawn(f)
#=> #PID<0.40.0>

#開啟的shell本身也是一個process, 你可以透過self() 取得它的process
self() #=> #PID<0.27.0>

在上述例子,是一個簡單folk process的範例。但是以上尚未實作receive的部分,
接下來是一個實作message send & recevie的例子。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# receiver 範例
defmodule Welcome do
  def enterto do
    receive do
      {:vip, name} ->
        IO.puts "HI, #{name} 貴賓您好! "
        enterto()
      {:normal, name} ->
        IO.puts "HI, #{name} 歡迎光臨! "
        enterto()
      { _, name}  ->
        IO.puts "Sorry #{name}, 我不認識你"
        enterto()
    end
  end
end

1
2
3
4
5
6
7
8
9
#嘗試send name & 不同type去剛剛實作的Welcome module
pid = spawn(fn -> Welcome.enterto() end)

send pid, {:vip, "聖蚊"}
#=>  HI, 聖蚊 貴賓您好!
send pid, {:normal, "釩人"}
#=> HI, 釩人 歡迎光臨!
send pid, {:nothing, "魯蛇"}
#=> Sorry 魯蛇, 我不認識你

參考資料Learn X in Y minutes.

在上&下中 我只有介紹一些基礎的部分,
Elixir還有許多很酷的部分 , 像是node distribution, OTP … 等.
有機會的話我會在後續的文章中再做介紹. 很歡迎如果你對於這個語言有興趣的話.可以跟我一起交流。

可能有興趣的文章: