4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Elixir Enum.sliceの紹介

Last updated at Posted at 2024-10-13

こんにちは!
プログラミング未経験文系出身、Elixirの国に迷い込んだ?!見習いアルケミストのaliceと申します。
今回はEnum.sliceについて学んだことをまとめます。
2024/10/13に開催したイベントpiyopiyo.ex #46:もくもく作業タイムの成果です。

目的

Enum.sliceの使いどころを理解する。

実行環境

Windows 11 + WSL2 + Ubuntu 22.04
Elixir v1.17.0
Erlang v27.0

前提

あらかじめ下記の変数を定義しておきます

iex
cart = [
  %{fruit: "apple", count: 3},
  %{fruit: "banana", count: 1},
  %{fruit: "orange", count: 6}
]

Enum.slice/2

Enum.slice(enumerable, index_range)は、

  • enumerableのうちindex_range(ゼロベース)の範囲を要素を取り出し、リストにして返す
  • index_rangeが負の値の場合、要素を後ろから数える
  • index_rangeenumerableの要素数の範囲外にあたる場合、ヒットした要素だけ取り出す

例1

iex
Enum.slice(cart, 0..1)
[%{count: 3, fruit: "apple"}, %{count: 1, fruit: "banana"}, %{count: 6, fruit: "orange"}]

例2

iex
Enum.slice(cart, -2..-1)
[%{count: 1, fruit: "banana"}, %{count: 6, fruit: "orange"}]

Enum.slice/3

Enum.slice(enumerable, start_index, amount)は、

  • enumerableのうちstart_index(ゼロベース)を数えた地点を開始地点とし、amount個ぶんのを要素を取り出し、リストにして返す
  • start_indexが負の値の場合要素を後ろから数えた地点を開始地点とする
  • amountに負の値は指定できない

例1

iex
Enum.slice(cart, 1, 2)
[%{count: 1, fruit: "banana"}, %{count: 6, fruit: "orange"}]

例2

iex
Enum.slice(cart, -2, 2)
[%{count: 1, fruit: "banana"}, %{count: 6, fruit: "orange"}]

例3

iex
Enum.slice(1..1000,-10, 3)
[991, 992, 993]

例4

iex
Enum.slice(1..1000,-10, -3)
** (FunctionClauseError) no function clause matching in Enum.slice/3    

~Elixirの国のご案内~

↓Elixirって何ぞや?と思ったらこちらもどぞ。Elixirは先端のアレコレをだいたい全部できちゃいます:laughing::sparkles::sparkles:

↓ゼロからElixirを始めるなら「エリクサーチ」がおすすめ!私もエンジニア未経験から学習中です。

We Are The Alchemists, my friends!:bouquet:1
Elixirコミュニティは本当に優しくて温かい人たちばかり!
私が挫折せずにいられるのもこの恵まれた環境のおかげです。
まずは気軽にコミュニティを訪れてみてください。2

  1. @torifukukaiouさんのAwesomeな名言をお借りしました。Elixirコミュニティを一言で表すと、これに尽きます。

  2. @kn339264さんの素敵なスライドをお借りしました。Elixirコミュニティはいろんな形で活動中!

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?