5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

草莽Erlang ── 04. タプル

Last updated at Posted at 2023-01-03

口で言うより行うことがErlang習得への近道と信じています。

タプルとは

タプルはデータを整理する方法の一つです。メモリ上に連続的に格納されます。このため、タプルの長さを得るのは高速ですが、修正を行うのは高コストとなります。新しいタプルは全ての要素がメモリにコピーされるからです。タプルは波括弧({})を用いて定義されます。

> Point = {8, 4}.
{8,4}

タプルの長さは tuple_size/1 で取得します。

> tuple_size(Point).
2

タプルの要素は element/2 で取得します。要素の数え方は「1、2、3ぁっダー!」です。最初の要素のインデックスは1となります。

> element(1, Point).
8

> element(2, Point).
4

パターンマッチを扱う時によりタプルの有用性を享受することができます。

> Temperature = {celsius, 25.123}.
{celsius,25.123}

> {celsius, Tc} = Temperature.
{celsius,25.123}

> {kelvin, Tk} = Temperature.
** exception error: no match of right hand side value {celsius,23.213}

タプルは関数から付加的な情報を返す仕組みとしてよく利用されます。以下はfile:read_file/1でファイルを読み込む例です。

> file:read_file("path/to/existing/file").
{ok,"content"}

> file:read_file("path/to/unknown/file").
{error,enoent}

Elixirにも挑戦したい

闘魂ElixirシリーズとElixir Schoolがオススメです。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?