Elixir multiplication in a Map does not work. Because?

1

I'm new to Elixir and I do not understand the return of the function.

list = %{"100" => 1, "50" => 2, "20" => 4, "10" => 8, "5" => 16, "1" => 32}

for {key, value} <- list, do: String.to_integer(key) * value

Or

Enum.map(list, fn({key, value}) -> String.to_integer(key) * value end)

Returns

' PdPPd'

But when I convert to String

for {key, value} <- list, do: "#{String.to_integer(key) * value}"

Returns

["32", "80", "100", "80", "80", "100"]
    
asked by anonymous 01.04.2018 / 17:25

1 answer

2

Both codes work properly, as can be seen here . The problem you are experiencing occurs when you view the results.

When you use IO.inspect in an integer collection, Elixir attempts to convert these values to strings . As the values in your example are valid code points in the ascii table, they end up being converted into the corresponding characters (32: space, 80: P, 100: d, etc.).

To prevent this from occurring, you can add the char_lists: :as_lists option. Example:

IO.inspect Enum.map(list, fn{key, value} -> String.to_integer(key) * value end) , char_lists: :as_lists
    
03.04.2018 / 05:20