Skip to content

Instantly share code, notes, and snippets.

@okabe-yuya
Created May 27, 2023 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okabe-yuya/aedebea08559beb411d58cef7ba07e77 to your computer and use it in GitHub Desktop.
Save okabe-yuya/aedebea08559beb411d58cef7ba07e77 to your computer and use it in GitHub Desktop.
有限状態機械のサンプルコード
defmodule StateServer do
@transitions %{
initial: %{ receive_order: :check_stock },
check_stock: %{ purchase: :ready_for_snipment },
ready_for_snipment: %{ snipment: :package_arrive },
package_arrive: %{ initial: :initial }
}
def run do
spawn(fn -> server(:initial) end)
end
def server(state) do
receive do
{ :msg, type, from } ->
next = Map.get(@transitions, state) |> Map.get(type, state)
send(from, next)
server(next)
end
end
end
# client
server_pid = StateServer.run()
send(server_pid, { :msg, :receive_order, self() })
send(server_pid, { :msg, :purchase, self() })
send(server_pid, { :msg, :snipment, self() })
send(server_pid, { :msg, :initial, self() })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment