1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

wslでelixir その47

Last updated at Posted at 2023-09-05

概要

wsl(wsl2じゃない)で、elixirやってみた。
Cizen、やってみた。

サンプルコード


defmodule Push do
	defstruct [:item]
end

defmodule Pop do
	defstruct []
	use Cizen.Request
	defresponse Item, :pop_event_id do
		defstruct [:item, :pop_event_id]
	end
end

defmodule Stack do
	use Cizen.Automaton
	defstruct [:stack]
	use Cizen.Effects
	alias Cizen.Event
	alias Cizen.Filter
	@impl true
	def spawn(id, %__MODULE__{stack: stack}) do
		perform id, %All{effects: [
			%Subscribe{event_filter: Filter.new(fn %Event{body: %Push{}} -> 
				true 
			end)},
			%Subscribe{event_filter: Filter.new(fn %Event{body: %Pop{}} -> 
				true 
			end)}
		]}
		stack
	end
	@impl true
	def yield(id, stack) do
		event = perform id, %Receive{}
		case event.body do
			%Push{item: item} ->
				[item | stack]
			%Pop{} ->
				[item | tail] = stack
				perform id, %Dispatch{
					body: %Pop.Item{item: item, pop_event_id: event.id}
				}
				tail
		end
	end
end

defmodule Main do
	def main do
		use Cizen.Effectful
		use Cizen.Effects
		handle fn id ->
			perform id, %Start{
				saga: %Stack{stack: [:a]}
			}
			item_event = perform id, %Request{
				body: %Pop{}
			}
			%Pop.Item{item: item} = item_event.body
			IO.puts(item)
			perform id, %Dispatch{
				body: %Push{item: :b}
			}
			perform id, %Dispatch{
				body: %Push{item: :c}
			}
			item_event = perform id, %Request{
				body: %Pop{}
			}
			%Pop.Item{item: item} = item_event.body
			IO.puts(item)
			item_event = perform id, %Request{
				body: %Pop{}
			}
			%Pop.Item{item: item} = item_event.body
			IO.puts(item)
		end
	end
end


実行結果

$ iex -S mix
Erlang/OTP 25 [erts-13.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [jit:ns]

Compiling 1 file (.ex)
Generated testcizen app
Interactive Elixir (1.13.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Main.main
a
c
b
:ok
iex(2)>
BREAK: (a)bort (A)bort with dump (c)ontinue (p)roc info (i)nfo
       (l)oaded (v)ersion (k)ill (D)b-tables (d)istribution
a

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?