Erlang vs Elixir by example – kv store

lidashuang發表於2019-02-16

《Erlang程式設計》第十章kvs的例子

Erlang實現:

-module(kvs).
-export([start/0, store/2, lookup/1]).

start() -> register(kvs, spawn(fun() -> loop() end)).

store(Key, Value) -> rpc({store, Key, Value}).

lookup(Key) -> rpc({lookup, Key}).

rpc(Q) ->
    kvs ! {self(), Q},
    receive
        {kvs, Reply} ->
            Reply
    end.

loop() ->
    receive
        {From, {store, Key, Value}} ->
            put(Key, {ok, Value}),
            From ! {kvs, true},
            loop();
        {From, {lookup, Key}} ->
            From ! {kvs, get(Key)},
            loop()
    end.

Elixir實現

defmodule Kvs do
  def store(key, value) do
    rpc({:store, key, value})
  end

  def start do
    Process.register spawn(fn -> loop() end), :kvs
  end

  def lookup(key) do
    rpc({:lookup, key})
  end

  defp rpc(q) do
    send :kvs, {self(), q}
    receive do
      {:kvs, reply} ->
        reply
    end
  end

  defp loop do
    receive do 
      {form, {:store, key, value}} ->
        Process.put key, value
        send form, {:kvs, true}
        loop()
      {form, {:lookup, key}} ->
        send form, {:kvs, Process.get key}
        loop()
    end
  end
end 

使用Elixir更易讀,易懂

注意

  • Elixir中module名要大寫開頭
  • 不匯出的函式即私有函式使用defp定義
  • Elixir程式相關操作使用Process 模組
  • Eralng原子在Elixir形式是 :name

測試:

iex(1)> c("kvs.ex")
[Kvs]
iex(2)> Kvs.start
true
iex(3)> Kvs.store "a", 1
true
iex(4)> Kvs.lookup "a"
1
iex(5)>

相關文章