请在Iex中有一个默认启用千位分组的开关(例如100_000)。如果是这样的话,那将真的很有帮助。

否则我们如何在IO.puts中指定它?

最佳答案

如您根据 Inspect.Opts 所述,没有本机选项可启用数字分组。

但是,如果将IExIntegerFloat一起使用,则以下内容应该可以覆盖它们的检查行为:如果将其放置在本地~/.iex.exs文件中:

defmodule PrettyNumericInspect do
  def group(value, :binary, true),
    do: value |> group_by(8)
  def group(value, :decimal, true),
    do: value |> group_by(3)
  def group(value, :hex, true),
    do: value |> group_by(2)
  def group(value, :octal, true),
    do: value |> group_by(4)
  def group(value, _, _),
    do: value

  defp group_by(value, n) when byte_size(value) > n do
    size = byte_size(value)
    case size |> rem(n) do
      0 ->
        (for << << g :: binary-size(n) >> <- value >>,
          into: [],
          do: g)
        |> Enum.join("_")
      r ->
        {head, tail} = value |> String.split_at(r)
        [head, group_by(tail, n)] |> Enum.join("_")
    end
  end
  defp group_by(value, _),
    do: value
end

defimpl Inspect, for: Float do
  def inspect(thing, %Inspect.Opts{pretty: pretty}) do
    [head, tail] = IO.iodata_to_binary(:io_lib_format.fwrite_g(thing))
    |> String.split(".", parts: 2)
    [PrettyNumericInspect.group(head, :decimal, pretty), tail]
    |> Enum.join(".")
  end
end

defimpl Inspect, for: Integer do
  def inspect(thing, %Inspect.Opts{base: base, pretty: pretty}) do
    Integer.to_string(thing, base_to_value(base))
    |> PrettyNumericInspect.group(base, pretty)
    |> prepend_prefix(base)
  end

  defp base_to_value(base) do
    case base do
      :binary  -> 2
      :decimal -> 10
      :octal   -> 8
      :hex     -> 16
    end
  end

  defp prepend_prefix(value, :decimal), do: value
  defp prepend_prefix(value, base) do
    prefix = case base do
      :binary -> "0b"
      :octal  -> "0o"
      :hex    -> "0x"
    end
    prefix <> value
  end
end

必须将Inspect.Opts选项:pretty设置为true才能显示数字分组。根据 IEx.configure/1 的文档,默认情况下应启用漂亮检查。

启动iex时,您将看到2条有关重新定义Inspect.FloatInspect.Integer的警告,但此后它仍将继续正常工作:

iex> 100_000
100_000
iex> 100_000.1
100_000.1

它还支持针对不同:base选项(:binary:decimal:octal:hex)的分组:

iex> inspect 0b11111111_11111111, base: :binary, pretty: true
"0b11111111_11111111"
iex> inspect 999_999, base: :decimal, pretty: true
"999_999"
iex> inspect 0o7777_7777, base: :octal, pretty: true
"0o7777_7777"
iex> inspect 0xFF_FF, base: :hex, pretty: true
"0xFF_FF"

关于formatting - 在Iex中是否有默认启用千位分组(100_000)的开关,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34064900/

10-13 08:19