Skip to content

Instantly share code, notes, and snippets.

@fujimisakari
Last active April 18, 2017 15:51
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 fujimisakari/7699692785324f6d97ad3dcd8ce2beef to your computer and use it in GitHub Desktop.
Save fujimisakari/7699692785324f6d97ad3dcd8ce2beef to your computer and use it in GitHub Desktop.

プログラミングErlang - 属性

4章あたり。
Erlang のモジュールの呼び出し、属性の定義、属性の構文など

属性

モジュール属性はAtomTag(...)という構文で指定し、ファイルをいくつかの属性を定義するために使われる。
モジュール属性には、定義済みとユーザ定義の2つの種類がある

定義済みのモジュール属性

-module(modname).

  • モジュール宣言
  • modname はアトムでなければならない。
  • この属性はファイルの最初の属性でなければならない。
  • modname モジュールのコードはmodname.erl という名前のファイルに格納するのが慣習になっている。
  • この習慣に従わないと、自動コードロード機構が正しく機能しない。

-import(Mod, [Name1/Arity1, Name2/Arity2,....]).

  • Arity1個の引数を持つ関数Name1 をモジュールMod からインポートすることを指定する。
  • モジュールから関数をインポートすると、その関数はモジュール名を指定しなくても呼び出せるようになる。
-module(abc).
-import(lists, [map/2]).

f(L) -> L1 = map(fun(X) -> 2*X end, L),
lists:sum(L1)

-export([Name1/Arity1, Name2/Arity2, ...]).

  • 関数Name1/Arity1 、Name2/Arity2 などを現在のモジュールからエクスポートする。
  • モジュールの外部から呼び出せるのはエクスポートされた関数だけ
Icode/abc.erl
-module(abc).
-export([a/2, b/1]).

a(X, Y) -> c(X) + a(Y).
a(X) -> 2 * X.
b(X) -> X * X.
c(X) -> 3 * X.
%% このエクスポート宣言は、モジュールabc の外部から呼び出せるのはa/2 とb/1 だけであることを意味する

-compile(Options).

  • コンパイラオプションのリストにOptionsを追加する。
  • Optionsはコンパイラオプション1つ、またはコンパイラオプションのリスト。
  • コンパイラオプション-compile(export_all). はプログラムをデバッグするときに使うことが多い。

-vsn(Version).

  • モジュールのバージョンを指定する。
  • Version はリテラルの項ならば何でもよい。
  • Version の値には特に構文や意味はないが、分析プログラムやドキュメント用途などに利用できる。

ユーザ定義の属性

%% 構文
-SomeTag(Value).
  • SomeTagはアトムでなければならず、Valueはリラテルな項でなければならない
  • モジュール属性の値はコンパイルしてモジュールに埋め込まれ、実行時に取り出すことができる

・attrs.erl

-module(attrs).
-vsn(1234).
-author({fujimisakari}).
-purpose("example of attributes").
-export([fac/1]).

fac(1) -> 1;
fac(N) -> N * fac(N-1).

・Eshell

1> attrs:module_info().
[{module,attrs},
 {exports,[{fac,1},{module_info,0},{module_info,1}]},
 {attributes,[{vsn,[1234]},
              {author,[{fujimisakari}]},
              {purpose,"example of attributes"}]},
 {compile,[{options,[]},
           {version,"7.0.4"},
           {source,"/Users/fujimisakari/dev/erlang/attrs.erl"}]},
 {native,false},
 {md5,<<206,189,170,36,103,236,83,182,14,45,135,93,102,1,
        177,185>>}]
2> attrs:module_info(attributes).
[{vsn,[1234]},
 {author,[{fujimisakari}]},
 {purpose,"example of attributes"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment