【问题标题】:Is there a Switch to enable thousand digit grouping (100_000) by default in IexIex中是否有默认启用千位分组(100_000)的开关
【发布时间】:2016-03-08 00:03:18
【问题描述】:

请在 Iex 中默认启用千位分组(例如100_000)的开关。如果是的话,那将是非常有帮助的。

要不然怎么在IO.puts指定呢?

【问题讨论】:

  • 不是答案,而是在 iex 中键入“h(Iex)”(减去双引号)——这将为您提供更多关于在 iex 中可以做什么的详细信息。您也可以键入 h(IO.puts)。我认为简单的答案是在这两种情况下都没有这样的开关。
  • 谢谢,其实是:h(IEx)
  • 这是我输入的。
  • 实际上没有...... h(Iex) 会出错,它是 h(IEx) 有效(至少在 Windows 上)
  • 哦--duh。我现在跟着你。如果我可以编辑我的评论,我会的。

标签: formatting elixir elixir-iex


【解决方案1】:

没有根据Inspect.Opts 描述的启用数字分组的本机选项。

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

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多