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


はじめに

"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"
  • は嫌だなと
    • ~wって、なんだろう? という方はリンク先をご参照ください

結論

  • これでどうでしょうか
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)
    • は同じ意味の無名関数です
  • もっと簡潔に書けるよ! ってことをご存知の方いらっしゃいましたら、ぜひ教えてください

参考

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>>でハハーんとなりました

Wrapping Up 🎍🎍🎍🎍🎍


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