3
0

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 3 years have passed since last update.

文字列配列を長さ&五十音順にソートする(Elixir)

Posted at

はじめに

  • @tsukada_cs さんの文字列配列を長さ&五十音順にソートするを拝見しまして、私はElixirでやってみました
    • タプルの比較について理解を深めることとなりました
  • IExでやってみます
  • Elixir1.10.4を使っています
  • 一瞬どうやってやればいいのかわからなかったのですが、Pythonで書かれた元の記事を参考に書いてみることで同じ結果が得られました
iex> words = ["にほん", "あめりか", "ろしあ", "ふらんす", "いたりあ", "ちゅうごく", "しんがぽーる", "おーすとらりあ", "たい", "ちり", "どいつ", "いぎりす"]

iex> Enum.sort_by(words, fn word -> {String.length(word), word} end)  
["たい", "ちり", "どいつ", "にほん", "ろしあ", "あめりか",
 "いぎりす", "いたりあ", "ふらんす", "ちゅうごく",
 "しんがぽーる", "おーすとらりあ"]

iex> Enum.sort_by(words, &({String.length(&1), &1}))                
["たい", "ちり", "どいつ", "にほん", "ろしあ", "あめりか",
 "いぎりす", "いたりあ", "ふらんす", "ちゅうごく",
 "しんがぽーる", "おーすとらりあ"]
  • タプルの比較とは何だろうと思って調べたところ、こちらにさらっと記載がありました

The collection types are compared using the following rules:

  • Tuples are compared by size, then element by element.

サイズが大きいものが大きい、サイズが同じなら各要素の比較になるよ(先頭から決着がついたらそれが比較結果さ)と言っています。

iex> {0, 0, 0} > {10000000}
true

iex> {1000000000} > {-1, -1}
false

iex> {0, -100} > {-1, -1}         
true

Wrapping Up

  • タプルの比較を学びました :tada::lgtm::tada::lgtm::tada::lgtm:
  • Enjoy Elixir!!! :rocket::rocket::rocket:
3
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?