LoginSignup
2
2

More than 5 years have passed since last update.

Elixirの Enum の主な関数の使い方の覚え書き

Last updated at Posted at 2015-11-11

Enumcollectionを引数に取る主要な関数を下記に記載してみる。

Collectionの指定した位置の値を返す

iex(1)> Enum.at([1,2,5,4],0)
1
iex(2)> Enum.at([1,2,5,4],1)
2
iex(3)> Enum.at([1,2,5,4],2)
5
iex(4)> Enum.at([1,2,5,4],3)
4
iex(5)> Enum.at([1,2,5,4],4)
nil

Collectionの指定した位置の値を返す(タプルでステータスも返る)

iex(1)> Enum.at([1,2,5,4], 2)   
5
iex(2)> Enum.fetch([1,2,5,4], 2)
{:ok, 5}

iex(3)> Enum.at([1,2,5,4], 4)   
nil
iex(4)> Enum.fetch([1,2,5,4], 4)
:error

Collectionの値をソートする

iex(1)> Enum.sort([1,2,5,4])
[1, 2, 4, 5]

Collectionの数を返す

iex(1)> Enum.count([1,2,5,4])
4

Collectionの最大値/最小値を返す

iex(1)> Enum.max([1,2,5,4])                          
5
iex(2)> Enum.min([1,2,5,4])
1

Collectionにセパレータを付加する

iex(1)> Enum.join([1,2,5,4],"/")
"1/2/5/4"
iex(2)> Enum.join([1,2,5,4],"-")
"1-2-5-4"

Collectionの先頭から指定した数の値を削除する

iex(1)> Enum.drop([1,2,5,4], 0)
[1, 2, 5, 4]
iex(2)> Enum.drop([1,2,5,4], 1)
[2, 5, 4]
iex(3)> Enum.drop([1,2,5,4], 3)
[4]

Collectionの値をランダムに返す

iex(1)> Enum.shuffle([1,2,5,4])
[1, 5, 4, 2]
iex(2)> Enum.shuffle([1,2,5,4])
[4, 1, 2, 5]
iex(3)> Enum.shuffle([1,2,5,4])
[1, 2, 5, 4]

Collectionが空かどうかを返す

iex(1)> Enum.empty?([]) 
true
iex(2)> Enum.empty?([1,2,5,4])
false
iex(3)> Enum.empty?([nil])
false

Collectionの先頭に挿入する

iex(1)> Enum.into([1,2,5,4], [9,8,7])                
[9, 8, 7, 1, 2, 5, 4]
2
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
2
2