Help us understand the problem. What is going on with this article?

Elixir Zen スタイル バイナリ+パターンマッチでバイナリデコーダを作ってみよう!

ではコード例をご紹介。MIDIシーケンサーの一部を書いてみました。

defmodule MidiDecoder do
  def decode(<<>>), do: []

  def decode(<<
    8::size(4),
    channel::bitstring-size(4),
    velocity::bitstring-size(8),
    rest::bitstring()
  >>) do
    [{:note_off, channel, velocity}] ++ decode(rest)
  end

  def decode(<<
    9::size(4),
    channel::bitstring-size(4),
    velocity::bitstring-size(8),
    rest::bitstring()
  >>) do
    [{:note_on, channel, velocity}] ++ decode(rest)
  end
  
end

まず

def decode(<<>>), do: []

これは再帰呼び出しを止めるために存在します。

次に

  def decode(<<
    8::size(4),
    channel::bitstring-size(4),
    velocity::bitstring-size(8),
    rest::bitstring()
  >>) do
    [{:note_off, channel, velocity}] ++ decode(rest)
  end

コメントで注釈を入れていきますね。

  def decode(<<
    8::size(4),                   # 4ビット取り出して値が8である場合
    channel::bitstring-size(4),   # 次の4ビットは channel に割り当てます
    velocity::bitstring-size(8),  # その次の8ビットは velocity に割り当てます
    rest::bitstring()             # 残りです。
  >>) do
    [{:note_off, channel, velocity}] ++ decode(rest)  # ノートオフを読み出せました
  end

では同様にこちらも読み解いてみましょう。

  def decode(<<
    9::size(4),
    channel::bitstring-size(4),
    velocity::bitstring-size(8),
    rest::bitstring()
  >>) do
    [{:note_on, channel, velocity}] ++ decode(rest)
  end

わかりました?

こんな感じで,バイナリ列にマッチするような条件分岐をスマートに書くことができます!

これを Elixir Zen スタイルの新しい仲間に加えたいと思います。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away