Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@upscent

Enum.sort または Enum.sort_by で安定ソートさせるために気をつけること

More than 3 years have passed since last update.

プログラミングElixir読み途中です。
引っかかりそうなところがあったのでメモしておきます。

Enum.sort/2 の第二引数には、同じ値の場合は true を返すようなを関数を渡さないと安定ソートになりません。

iex> words = ["some","kind","of","monster"]
["some", "kind", "of", "monster"]
iex> Enum.sort words, &(String.length(&1) < String.length(&2))
["of", "kind", "some", "monster"]
iex> Enum.sort words, &(String.length(&1) <= String.length(&2))
["of", "some", "kind", "monster"]

Enum.sort_by/3 でも同様です。

iex> words = ["some","kind","of","monster"]
["some", "kind", "of", "monster"]
iex> Enum.sort_by words, &String.length/1, &</2
["of", "kind", "some", "monster"]
iex> Enum.sort_by words, &String.length/1, &<=/2
["of", "some", "kind", "monster"]

Enum.html#sort/2 の Example には、このことが書いていますが、sort_byの方は特に何も書いてないので… sortの方も見ろやってことですかね(´・ω:;.:...

Enum.sort/2 not stable · Issue #2163 · elixir-lang/elixirのコメントにも書いてますが、自分もつい >=<= より >< を使うことが多いので気をつけます(`・ω・´)ゞ

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
upscent

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?