Input validation confusion!

First of all:

data = Enum.to_list(?0..?9) ++ Enum.to_list(?a..?z)

result = Enum.reduce(data, %{digits: %{}, symbols: %{}}, fn integer, acc ->
  letter = <<integer::utf8>>
  acc |> put_in([:digits, letter], integer) |> put_in([:symbols, integer], letter)
end)

@digits result.digits
@symbols result.symbols

With this you are iterating data only once and don’t have so huge badly formatted map. :077:

Look that Map.to_list/1 is one iteration, Enum.map/2 is second and Map.new/1 is third.

Secondly:

@digits Map.to_list(@symbols) |> Enum.map(fn {k, v} -> {v, k} end) |> Map.new()
# better
@digits @symbols |> Map.to_list() |> Enum.map(fn {k, v} -> {v, k} end) |> Map.new()

Finally:

unless num < base do
  from_decimal(div(num, base), base, result)
else
  result
end
# better
if num < base do
  result
else
  num |> div(base) |> from_decimal(base, result)
end

I also recommend to take a look at Erlang source if C is not a problem for you. :slight_smile:

You can start from: erts/emulator/beam/big.c:325 (in 22.0-rc.1 release). You can find there source of integer_to_binary/3 in which you can find more inspiration for further speed improvements.

Here is helpful resource:

in which I’m linking some style guides:

1 Like