LoginSignup
6
5

More than 5 years have passed since last update.

[Elixir]Pipe演算子とパターンマッチを組み合わせる

Posted at

Goal

Pipe演算子とパターンマッチを組み合わせて、実行できる関数を制限する。

Dev-Environment

OS: Windows8.1
Erlang: Eshell V6.4, OTP-Version 17.5
Elixir: v1.0.5

Wait a minute

Pipe演算子と関数のマッチング機能を使ったTips。
マクロの記事と言うには微妙だが・・・微妙に使ってますからね。

と言っても、参考文献に記載している、記事内ソースコードのコピペですが。

Index

Pipe operators and pattern match
|> Example code
|> Let's run!

Example code

サンプルを作成します。

Example

defmodule PipeSample do
  @status [
    # state: {action, next_state}
    running: {:run, :running},
    running: {:restart, :restart},
    running: {:stop, :stopped},
    restart: {:resume, :running}
  ]

  for {state, {action, next_state}} <- @status do
    def unquote(action)(unquote(state)), do: unquote(next_state)
  end

  def init, do: :running
end

Description

特定の引数を受け取らないとマッチしない関数を展開しています。
そのため、パイプでつないでいる、前の関数を制限している形になります。

実行結果を見れば分かりやすいと思います。

Let's run!

実行して結果を見てみます。

Result:

iex> import PipeSample
nil

初期化の関数だけ呼ぶ。

iex> init
:running

初期化して停止させる。

iex> init |> stop
:stopped

不正な処理の流れ。

iex> init |> run |> resume
** (FunctionClauseError) no function clause matching in PipeSample.resume/1
    05_pipe_sample.ex:11: PipeSample.resume(:running)

色々組み合わせてみる。

iex> init |> run |> restart |> resume |> run |> stop
:stopped

Speaking to oneself

これだけです。
まぁ、もしかしたらどこかで使えるかもしれないし、使えないかもしれない。

Bibliography

The Erlangelist - UNDERSTANDING ELIXIR MACROS, PART 1 - BASICS

6
5
1

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
6
5