Getting StartedでElixirを学習しています。
基本型
7つの基本型の例です
- 整数型(integer) → 10
- 浮動小数点型(float) → 10.0
- 論理型(boolean) → true
- アトム型(atom) → :atom
- 文字列型(binary) → "hello"
- リスト型(list) → [1, 2, 3, 4]
- タプル型(tuple) → {1, 2, 3, 4}
基本算術
iex> 1 + 1 2 iex> 2 - 1 1 iex> 3 * 3 9 iex> 4 / 2 2.0
/による除算は常に浮動小数点型を返します。
整数で除算の結果や剰余を得たい場合はdiv/2やrem/2関数を用います。
iex> div(5, 2) 2 iex> rem(5, 2) 1
Elixirの浮動小数点型は64ビットの倍精度です。
round/1関数は与えられた浮動小数点数に対して最も近い整数を返します。
trunc/1関数は与えられた浮動小数点数の整数部分を返します。
iex> round(1.45) 1 iex> round(1.55) 2 iex> trunc(1.99) 1
関数の識別と説明文書の取得
関数は関数の名前とアリティの両方で識別されます。アリティは関数が受け取る引数の数です。
四則演算で例示した、div/2、rem/2、round/1、trunc/1のように記載します。
Elixirシェルのh/1関数は与えられた関数の説明文書を返します。
iex> h trunc def trunc(number) @spec trunc(value) :: value when value: integer() @spec trunc(float()) :: integer() guard: true Returns the integer part of number. Allowed in guard tests. Inlined by the compiler. ## Examples iex> trunc(5.4) 5 iex> trunc(-5.99) -5 iex> trunc(-5) -5
論理値型
真はtrueで、偽はfalseです。頭文字は小文字です。
Elixirには値の型をチェックする関数があります。
論理値型であるかをチェックする関数はis_boolean/1です。
iex> is_boolean(true) true iex> is_boolean(True) false
アトム型
アトムは名前に対応した値が対応する定数です。他のいくつかの言語ではシンボルと呼ばれています。
次のような個別の値を列挙するのに役立ちます。
iex> :apple :apple iex> :orange :orange iex> :rasberry :rasberry iex>