3
0

More than 3 years have passed since last update.

"A"から"Z"のうちでindex=10のアルファベットはなに? (Elixir)

Last updated at Posted at 2021-01-10

はじめに

"A"から"Z"のうちでindex=10のアルファベットはなに?

Ruby

  • まずはRuby先輩
irb(main):006:0> ('A'..'Z').to_a[10]
=> "K"

Elixir

iex> "A".."Z"
** (ArgumentError) ranges (first..last) expect both sides to be integers, got: "A".."Z"
    (elixir 1.11.2) lib/kernel.ex:3467: Kernel.range/3
    (elixir 1.11.2) expanding macro: Kernel.".."/2
    iex:1: (file)
  • Ruby先輩っぽい書き方はコンパイルエラーになりました1
iex> ~w(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
 "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

iex> ~w(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) |> Enum.at(10)
"K"
  • :point_up::point_up_tone1::point_up_tone2::point_up_tone3::point_up_tone4::point_up_tone5: は嫌だなと:sweat_smile:
    • ~wって、なんだろう? という方はリンク先をご参照ください

結論

  • これでどうでしょうか :point_down::point_down_tone1::point_down_tone2::point_down_tone3::point_down_tone4::point_down_tone5:
iex> (?A..?Z) |> Enum.at(10) |> (&<<&1>>).() 
"K"

iex> (?A..?Z) |> Enum.at(10) |> (fn c -> <<c>> end).()
"K"
  • 何でもpipe operator |>で書ききってしまいたい症候群です
    • (&<<&1>>)
    • (fn c -> <<c>> end)
    • は同じ意味の無名関数です
  • もっと簡潔に書けるよ! ってことをご存知の方いらっしゃいましたら、ぜひ教えてください :pray::pray_tone1::pray_tone2::pray_tone3::pray_tone4::pray_tone5:

参考

iex> i "K"
Term
  "K"
Data type
  BitString
Byte size
  1
Description
  This is a string: a UTF-8 encoded binary. It's printed surrounded by
  "double quotes" because all UTF-8 encoded code points in it are printable.
Raw representation
  <<75>>
Reference modules
  String, :binary
Implemented protocols
  Collectable, IEx.Info, Inspect, List.Chars, String.Chars
  • Raw representation<<75>>でハハーんとなりました :relaxed:

Wrapping Up 🎍🎍🎍🎍🎍


  1. Rangeは整数が指定されることを期待しています。https://github.com/elixir-lang/elixir/blob/v1.11.3/lib/elixir/lib/range.ex#L57-L66 

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