5
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?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-01-02

プログラミング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のコメントにも書いてますが、自分もつい >=<= より >< を使うことが多いので気をつけます(`・ω・´)ゞ

5
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
5
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?