LoginSignup
14
0

More than 1 year has passed since last update.

今日のElixirSchoolメモ17「Erlangとの相互運用」

Last updated at Posted at 2022-12-24

Elixir Schoolの学習メモです。

概要

Erlang VM(BEAM)の上で開発することによって得られる利点の1つに、既にある大量のライブラリが利用できるということが挙げられる。
相互運用できることで、そうしたライブラリはErlangの標準ライブラリをElixirコードから活用することができる。

標準ライブラリ

Erlangの豊富な標準ライブラリはアプリケーション内のどのElixirコードからもアクセスすることができる。
Erlangモジュールは:os:timerのように小文字のアトムで表される。

iex(1)> defmodule Example do
...(1)>   def timed(fun, args) do
...(1)>     {time, result} = :timer.tc(fun, args)
...(1)>     IO.puts("Time: #{time} μs")
...(1)>     IO.puts("Result: #{result}")
...(1)>   end
...(1)> end
{:module, Example,
 <<70, 79, 82, 49, 0, 0, 7, 104, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 243,
   0, 0, 0, 26, 14, 69, 108, 105, 120, 105, 114, 46, 69, 120, 97, 109, 112, 108,
   101, 8, 95, 95, 105, 110, 102, 111, 95, ...>>, {:timed, 2}}
iex(2)> Example.timed(fn (n) -> (n * n) * n end, [100])
Time: 5 μs
Result: 1000000
:ok

Erlangの利用可能なモジュールの一覧はErlang Reference Manualを参照する。

Erlangパッケージ

Erlangライブラリも組み込むことができる。

def deps do
  [{:png, github: "yuce/png"}]
end

注目すべき違い

アトム

Elixir:

:exmample

Erlang:

example.

文字列

Elixirの文字列はUTF-8でエンコードされたバイナリを意味するが、
Erlangでもstringはダブルクォートを使って表すが、文字リストを指す。

古いErlangライブラリではバイナリに対応していないものも多いため、
Elixirの文字列は to_charlist/1 関数を用いて、文字リストに変換する必要がある。

変数

Erlangでは、変数は大文字で始まり、バインドし直すことができない。

14
0
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
14
0