Elixir multiplication on a Map does not work. Why?

Asked

Viewed 112 times

1

I’m new to Elixir and I don’t understand the return of 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"]
  • Do you want to keep order or do you want something functional? The result came out as expected, since the order is not mandatory to follow in this construction.

1 answer

2


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

When you use it IO.inspect in a collection of integers, Elixir tries to convert these values into strings. As the values of 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 happening, you can add the option char_lists: :as_lists. Example:

IO.inspect Enum.map(list, fn{key, value} -> String.to_integer(key) * value end) , char_lists: :as_lists
  • Thanks!! Thanks for the suggestion really did not know.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.