LoginSignup
12
0

More than 1 year has passed since last update.

あふことの絶えてしなくばなかなかに人をも身をも恨みざらまし

Advent Calendar 2022 96日目1の記事です。
I'm looking forward to 12/25,2022 :santa::santa_tone1::santa_tone2::santa_tone3::santa_tone4::santa_tone5:
私のAdvent Calendar 2022 一覧


はじめに

Elixirを楽しんでいますか:bangbang::bangbang::bangbang:

今日はEnum.slide/3について書きます。

Enum.slide/3

Elixir 1.13 or laterです。

公式の説明をそのまま載せます。

スクリーンショット 2022-04-12 22.41.11.png

ざっくり言うとスライドさせる関数です。
私には難解でした。

Examples

例はひとつひとつ説明してみます。
リストは0オリジン(はじまり)です。

iex> Enum.slide([:a, :b, :c, :d, :e, :f, :g], 5, 1)
[:a, :f, :b, :c, :d, :e, :g]

indexが5の要素つまり:fをindex 1にいれます。
残りはスライドさせます。
うん、わかったね。
次行こう! 次!

# Slide a range of elements backward
iex> Enum.slide([:a, :b, :c, :d, :e, :f, :g], 3..5, 1)
[:a, :d, :e, :f, :b, :c, :g]

今度はRangeで指定です。
indexが3から5の要素つまり、[:d, :e, :f]をindex 1の位置にずらしています。

# Slide a range of elements forward
iex> Enum.slide([:a, :b, :c, :d, :e, :f, :g], 1..3, 5)
[:a, :e, :f, :b, :c, :d, :g]

今度もRangeの指定です。
indexが1から3の要素つまり、[:b, :c, :d]をindex 5の位置にずらしています。

# Slide with negative indices (counting from the end)
iex> Enum.slide([:a, :b, :c, :d, :e, :f, :g], 3..-1//1, 2)
[:a, :b, :d, :e, :f, :g, :c]

今度もRangeの指定です。
indexが3から末尾の要素つまり、[:d, :e, :f, :g]をindex 2の位置にずらしています。

iex> Enum.slide([:a, :b, :c, :d, :e, :f, :g], -4..-2, 1)
[:a, :d, :e, :f, :b, :c, :g]

今度もRangeの指定です。
indexが末尾が-1ですから-4..-2ってのはつまり[:d, :e, :f]ををindex 1の位置にずらしています。

# Insert at negative indices (counting from the end)
iex> Enum.slide([:a, :b, :c, :d, :e, :f, :g], 3, -1)
[:a, :b, :c, :e, :f, :g, :d]

indexが3の要素つまり:dを末尾にずらしています。

改めてEnum.slide/3の各引数の意味は以下の通りです。

  • 第1引数は、enumerable
  • 第2引数は、range_or_single_index
  • 第3引数は、insertion_index

以下はエラーになります。

iex> Enum.slide([:a, :b, :c, :d, :e, :f, :g], 3..5, 4)
** (RuntimeError) Insertion index for slide must be outside the range being moved (tried to insert 3..5 at 4)
    (elixir 1.13.1) lib/enum.ex:2619: Enum.slide/3

実装が気になる方は以下をご参照くださいませ。

プルリクはこちらです。

The classic use case is this: Suppose you have a list of to-do items, which the user has ordered by priority:

  1. Apply to college
  2. Brush the dog
  3. Change the car's oil
  4. Deliver flowers
  5. Exchange gifts

Wrapping up :lgtm::lgtm::lgtm::lgtm::lgtm:

今日は、Enum.slide/3を楽しんでみました。
私は動きを追うことで精一杯でした。
きっとどこかで使う場面がくるのでしょう。

こんなとき使ったよ! という事例をお持ちのかたはぜひお便り(コメント)をください。

Enjoy Elixir:bangbang::bangbang::bangbang:
$\huge{Enjoy\ Elixir🚀}$

以上です。


I organize autoracex.
And I take part in NervesJP, fukuoka.ex, EDI, tokyo.ex, Pelemay.
I hope someday you'll join us.

We Are The Alchemists, my friends!


  1. @kaizen_nagoya さんの「「@e99h2121 アドベントカレンダーではありますまいか Advent Calendar 2020」の改訂版ではありますまいか Advent Calendar 2022 1日目 Most Breakthrough Generator」から着想を得て、模倣いたしました。

12
0
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
12
0