大きい数字を読みやすいように漢字混じりの数字に変換するような
コードをElixirで書いてみました
defmodule Kansuuji do
@moduledoc """
Documentation for Kansuuji.
"""
@units ~w/万 億 兆 京/
@doc """
## Examples
iex> Kansuuji.parse 100
"100"
iex> Kansuuji.parse 10000
"1万"
iex> Kansuuji.parse 10001
"1万1"
iex> Kansuuji.parse 123456789
"1億2345万6789"
iex> Kansuuji.parse 100006789
"1億6789"
iex> Kansuuji.parse 98765100006789
"98兆7651億6789"
iex> Kansuuji.parse 98700100006789
"98兆7001億6789"
"""
def parse(num) do
num
|> Integer.to_string
|> String.graphemes
|> Enum.reverse
|> Enum.chunk_every(4)
|> Enum.map(fn x -> x |> Enum.reverse |> Enum.join end)
|> process(-1, "")
end
def process([], _, output) do
output
end
def process([h|t], -1, output) do
process(t, 0, zero_suppress(h))
end
def process([h | t], unit_index ,output) do
o = case zero_suppress(h) do
"" -> output
s -> "#{s}#{@units |> Enum.at(unit_index)}#{output}"
end
process(t, unit_index + 1, o)
end
def zero_suppress(s) do
h = s
|> String.replace(~r/^0+/, "")
end
end
最初の以下の操作を行い、 4桁くぎりの配列を作っています
- 与えられた数字を文字列に変換
- 文字列を文字ごとの配列に変換
- 配列の要素を逆転
- 配列を4桁ごとにチャンク
- チャンクされた配列の各要素をもとの文字列に戻す
そのあとはゼロサプレスしながら、空文字じゃなければ各単位を文字列にくっつけていって
あげている感じです。
こういったお遊びのときにもDoctestはすごい便利ですね