Strange behavior with String.to_integer / 1

I have something strange in Elixir with String.to_integer . Nothing serious, but I would like to know if there is a way to associate all my functions with the pipe operator.

Here is the problem. This line of code (you can try "iex"):

 [5, 6, 7, 3] |> Enum.reverse |> Enum.map_join "", &(Integer.to_string(&1)) 

returns the string "3765"

I want an integer. So I just need to add this little piece of code |> String.to_integer at the end of the previous statement, and I must have an integer. Give it a try. This piece of code:

 [5, 6, 7, 3] |> Enum.reverse |> Enum.map_join "", &(Integer.to_string(&1)) |> String.to_integer 

gives me this: "3765" Not an integer, a string!

If I do this:

 a = [5, 6, 7, 3] |> Enum.reverse |> Enum.map_join "", &(Integer.to_string(&1)) String.to_integer(a) 

Returns an integer: 3765 .

This is what I am doing right now, but it makes me go crazy because I would like to connect all these functions with a good pipe explorer.

Thanks for the help or the light. Elixir is very funny!

+7
elixir
source share
1 answer

You need to add parentheses around the map_join arguments. Your code is currently interpreted as

 [5, 6, 7, 3] |> Enum.reverse |> Enum.map_join("", &(Integer.to_string(&1) |> String.to_integer)) 

what do you want though

 [5, 6, 7, 3] |> Enum.reverse |> Enum.map_join("", &(Integer.to_string(&1))) |> String.to_integer 

Generally, you always need to use parentheses when you use captures inside a pipeline to avoid ambiguity. Capture can also be simplified to &Integer.to_string/1 :

 [5, 6, 7, 3] |> Enum.reverse |> Enum.map_join("", &Integer.to_string/1) |> String.to_integer 

But a simple Enum.join will do the same. If you look at the implementation , it will still convert integers to strings using the String.Chars protocol ..

 [5, 6, 7, 3] |> Enum.reverse |> Enum.join |> String.to_integer 

By the way, you can achieve the same without using strings at all:

 [5, 6, 7, 3] |> Enum.reverse |> Enum.reduce(0, &(&2 * 10 + &1)) 

Oh, and then Integer.digits and Integer.undigits , which can be used to convert an integer to and from a list of numbers. It is not present in the current release, although it is in the 1.1.0-dev branch, so I suspect it will go into 1.1.0 . You can see the progress here .

 [5, 6, 7, 3] |> Enum.reverse |> Integer.undigits 
+9
source share

All Articles