口で言うより行うことがErlang習得への近道と信じています。
型変換のためのビルトイン関数
Erlangには型変換のためのビルトイン関数がいくつかあります。
アトム ←→ 文字列
> atom_to_list(hello).
"hello"
> list_to_atom("hello").
hello
> "闘魂" = atom_to_list('闘魂').
[38360,39746]
> '闘魂' = list_to_atom("闘魂").
'闘魂'
整数 ←→ 文字列
> integer_to_list(123).
"123"
> list_to_integer("123").
123
> integer_to_list(255, 16).
"FF"
> list_to_integer("FF", 16).
255
浮動小数 ←→ 文字列
> list_to_float("7.12e+00").
7.12
> float_to_list(7.12).
"7.12000000000000010658e+00"
> float_to_list(7.12, [{decimals, 4}]).
"7.1200"
> float_to_list(7.12, [{decimals, 4}, compact]).
"7.12"
> float_to_list(7.12, [{scientific, 3}]).
"7.120e+00"
> float_to_list(7.12, [short]).
"7.12"
タプル ←→ リスト
> tuple_to_list({a, b, c}).
[a,b,c]
> list_to_tuple([a, b, c]).
{a,b,c}
何でもバイナリ変換
Erlangでは何でも簡単にバイナリに変換できます。
- binary_to_atom/1
- binary_to_atom/2
- binary_to_existing_atom/1
- binary_to_existing_atom/2
- binary_to_float/1
- binary_to_integer/1
- binary_to_integer/2
- binary_to_list/1
- binary_to_list-3
- binary_to_term/1
- binary_to_term/2
- atom_to_binary/1
- atom_to_binary/2
- float_to_binary/1
- float_to_binary/2
- integer_to_binary/1
- integer_to_binary/2
- iolist_to_binary/1
- list_to_binary/1
- term_to_binary/1
- term_to_binary/2
> binary_to_list(<<104,101,108,108,111>>).
"hello"
> list_to_binary("hello").
<<104,101,108,108,111>>
> term_to_binary({a, b, c}).
<<131,104,3,100,0,1,97,100,0,1,98,100,0,1,99>>
> binary_to_term(<<131,104,3,100,0,1,97,100,0,1,98,100,0,1,99>>).
{a,b,c}
Elixirにも挑戦したい
闘魂ElixirシリーズとElixir Schoolがオススメです。