書籍『すごいErlangゆかいに学ぼう!/Learn You Some Erlang for great good! 』まとめ
第4章 型(あるいはそれを欠いています)
4.1 動的で強い型付け
- Erlang は強い型付き言語
4.2 型変換
1> erlang:list_to_integer("54").
54
2> erlang:integer_to_list(54).
"54"
3> erlang:list_to_integer("54.32").
** exception error: bad argument
in function list_to_integer/1 called as list_to_integer("54.32") 4> erlang:list_to_float("54.32").
54.32
5> erlang:atom_to_list(true).
"true"
6> erlang:list_to_binary("hi there").
<<"hi there">>
7> erlang:binary_to_list(<<"hi there">>).
"hi there"
変換用関数一覧
- atom_to_binary/2
- atom_to_list/1
- binary_to_atom/2
- binary_to_existing_atom/2
- binary_to_list/1
- binary_to_term/1
- binary_to_term/2
- bitstring_to_list/1
- float_to_list/1
- fun_to_list/1
- integer_to_list/1
- integer_to_list/2
- iolist_to_atom/1
- iolist_to_binary/1
- list_to_atom/1
- list_to_binary/1
- list_to_bitstring/1
- list_to_existing_atom/1
- list_to_float/1
- list_to_integer/2
- list_to_pid/1
- list_to_tuple/1
- pid_to_list/1
- port_to_list/1
- ref_to_list/1
- term_to_binary/1
- term_to_binary/2
- tuple_to_list/1
4.3 データ型を守るために
型テスト BIF
- is_atom/1
- is_binary/1
- is_bitstring/1
- is_boolean/1
- is_builtin/3
- is_float/1
- is_function/1
- is_function/2
- is_integer/1
- is_list/1
- is_number/1
- is_pid/1
- is_port/1
- is_record/2
- is_record/3
- is_reference/1
- is_tuple/1
以下2つのコードは同じだが Erlang では後者が好まれる。
my_function(Exp) ->
case type_of(Exp) of
binary -> Expression1;
list -> Expression2
end.
my_function(Exp) when is_binary(Exp) -> Expression1; my_function(Exp) when is_list(Exp) -> Expression2.
4.4 型ジャンキーのために
第 30 章では簡単に Erlang で 静的型解析を行うツールである Dialyzer を紹介し、独 自の型を定義してより安全にコードを書く方法を紹介 します。