Elixir GUIDES を普通に読む1

Elixir GUIDES を読んだメモ

elixir-lang.jp

2.基本型

Elixir の関数は関数名とアリティで表す

  • アリティは引数の数
    • func/2 は関数名 func で引数を2つ取る関数

アトム

  • 他の言語でのシンボル、それ自身が定数でもある
    • :hello

無名関数

  • fn と end で区切る
iex(11)>  add = fn a, b -> a + b end       
#Function<13.126501267/2 in :erl_eval.expr/5>
iex(12)> add.(1,2)                         
3

13.126501267/2 <- これって関数名/アリティなのかな?

iex(13)>  add = fn a, b, c -> a + b + c end
#Function<19.126501267/3 in :erl_eval.expr/5>

そんな気がする

リスト

  • リストの要素はどんな型でも構わないらしい
iex(15)> [1, 2, true, 3]
[1, 2, true, 3]

すごい

  • ++/2--/2 でリストの足し引きができる
iex(17)> [1, 2, 3] ++ [4, 5, 6]
[1, 2, 3, 4, 5, 6]
iex(18)> [1, true, 2, false, 3, true] -- [true, false]
[1, 2, 3, true]
iex(19)> [1, true, 2, false, 3, true] -- [true, true] 
[1, 2, false, 3]
  • リストへの操作は新たなリストを返す
  • 元のリストは破壊しない

  • 出力可能な ASCII ナンバーが見つかると、Elixir はそれらを(文字リテラルのリスト)文字で出力します。

iex(20)>  i 'hello'
Term
  'hello'
Data type
  List
Description
  This is a list of integers that is printed as a sequence of characters
  delimited by single quotes because all the integers in it represent printable
  ASCII characters. Conventionally, a list of Unicode code points is known as a
  charlist and a list of ASCII characters is a subset of it.
Raw representation
  [104, 101, 108, 108, 111]
Reference modules
  List
Implemented protocols
  Collectable, Enumerable, IEx.Info, Inspect, List.Chars, String.Chars
  • シングルクォーテーションは文字リストでダブルクォーテーションは文字列らしい

  • i で型が見れるのかな?

iex(21)> i add
Term
  #Function<5.126501267/4 in :erl_eval.expr/5>
Data type
  Function
Type
  local
Arity
  4
Description
  This is an anonymous function.
Implemented protocols
  Enumerable, IEx.Info, Inspect

さっきの add

タプル

  • タプルはリストと同じように要素を持つ

    タプルの要素はメモリ上で隣接して保存されます。これによって、インデックスで要素にアクセスしたりタプルのサイズを得ることが高速になります。インデックスはゼロから始めます。

iex(22)> tuple = {:ok, "hello"}
{:ok, "hello"}
iex(23)> elem(tuple, 1)
"hello"

リスト or タプル

  • リストは連結リスト
  • 次の要素のポインタを持っている
iex(24)> list = [1, 2, 3]
[1, 2, 3]
iex(25)> [0] ++ list     
[0, 1, 2, 3]
  • 左側のリストを走査するので左のリストが短いほど高速

  • タプルはメモリ内で隣接して保持されている

  • サイズを得たりインデックスから要素にアクセスするのが容易
  • しかし、タプルに要素を追加するときは新しくタプルを作り直さなければならない