ElixirのGetting Startedをやろうと思いまして、そのメモです。
はじめに
Basic arithmetic
- floatは64bitの倍精度
-
/
演算子は常にfloatを返す
# integer
iex> 1
1
iex> 1_000_000
1000000
iex> 0xff
255
iex> 0xFF
255
iex> 0b11
3
iex> 0o77
63
# float
iex> 1.0
1.0
iex> 1.0e+4
1.0e4
iex> 1_000_000.001
1000000.001
# 演算
iex> 1 + 2
3
iex> 2 - 1
-1
iex> 0xff + 1
256
iex> 1 + 2.0
3.0
iex> 3 * 4
12
iex> 5 / 2
2.5
iex> div(5, 2)
2
iex> rem(5, 2)
1
iex> trunc 3.5
3
iex> trunc 3.4
3
iex> round 3.5
4
iex> round 3.4
3
Booleans
- Booleanは
true
/false
- 型チェックは
is_foobar/1
iex> true
true
iex> false
false
iex> is_boolean(1 == 1)
true
iex> is_boolean(1)
false
iex> is_float(5/2)
true
Atom
- Rubyではシンボル
-
true
/false
もシンボル
iex> :hello
:hello
iex> is_atom(false)
true
iex> is_boolean(:false)
true
Strings
- ダブルクォート
- UTF-8
- Ruby風のString interpolation
- バイナリとして扱われる
iex> "こんにちは"
"こんにちは"
iex> "hello #{:world}"
"hello world"
iex> IO.puts "こんにちは
...> 世界"
こんにちは
世界
:ok
iex> byte_size("こんにちは")
15
iex> String.length("こんにちは")
5
iex> String.upcase("Hello")
"HELLO"
Anonymous function
- 匿名関数の実行には
.
が必要 - 匿名関数はクロージャ
iex> add = fn a, b -> a + b end
# Function<12.54118792/2 in :erl_eval.expr/5>
iex> add.(1, 2)
3
iex> is_function(add)
true
iex> is_function(add, 1)
false
iex> is_function(add, 2)
true
iex> is_function(add, 3)
false
(Linked) Lists
- いわゆる片方向リスト
- 先頭への要素挿入は速い
- 要素数の計算には線形時間かかる
iex> [1, true, 1.0]
[1, true, 1.0]
iex> length [1, 2, 3]
3
iex> [1, 2, 3] ++ [4, 5, 6]
[1, 2, 3, 4, 5, 6]
iex> [1, true, 2, false, 3, true] -- [true, false]
[1, 2, 3, true]
iex> hd([1, 2, 3])
1
iex> tl([1, 2, 3])
[2, 3]
iex> [0] ++ [1,2,3] #速い
[0, 1, 2, 3]
iex> [1, 2, 3] ++ [4] #遅い(リスト全体の再構築が必要)
[1, 2, 3, 4]
- 表示可能なASCII番号のリストを表示するとき、文字リストとして表示する
- 文字リストと文字列は別物
iex> [97, 98, 99]
'abc'
iex> [97, 98, 99, 1]
[97, 98, 99, 1]
iex> is_list('abc')
true
iex> is_list("abc")
false
iex> 'abc' == "abc"
false
Tuples
- タプルの要素はメモリ上で連続した場所に保存される
- インデックスでアクセスできる
- インデックスでアクセスしたり、要素数の計算したりは速い
iex> tuple = {:ok, "hello"}
{:ok, "hello"}
iex> elem(tuple, 1)
"hello"
iex> tuple_size tuple
2
iex> put_elem(tuple, 1, "こんにちは")
{:ok, "こんにちは"}
iex> tuple
{:ok, "hello"}
その他
- 数を数える関数について、計算時間が
O(1)
となるものはsize
、それよりかかるものはlength
という名前が使われる