elixir - Strange behavior with String.to_integer/1 -
i have strange in elixir string.to_integer. nothing major, know if there's way chain functions pipe operator.
here problem. line of code (you can try in "iex"):
[5, 6, 7, 3] |> enum.reverse |> enum.map_join "", &(integer.to_string(&1)) returns string "3765"
what want integer. have add little piece of code |> string.to_integer @ end previous statement , should have integer. let's try. piece of code:
[5, 6, 7, 3] |> enum.reverse |> enum.map_join "", &(integer.to_string(&1)) |> string.to_integer gives me this: "3765". not integer, string!
if though:
a = [5, 6, 7, 3] |> enum.reverse |> enum.map_join "", &(integer.to_string(&1)) string.to_integer(a) it returns me integer: 3765.
it's i'm doing right makes me mad because love chain these function way amazing pipe operator.
thanks or lights. elixir fun!
you need add parentheses around arguments map_join. currently, code interpreted as
[5, 6, 7, 3] |> enum.reverse |> enum.map_join("", &(integer.to_string(&1) |> string.to_integer)) what want though
[5, 6, 7, 3] |> enum.reverse |> enum.map_join("", &(integer.to_string(&1))) |> string.to_integer generally, need use parentheses when using captures inside pipeline avoid ambiguities. capture can simplified &integer.to_string/1:
[5, 6, 7, 3] |> enum.reverse |> enum.map_join("", &integer.to_string/1) |> string.to_integer but plain enum.join same thing. if @ the implementation, convert integers strings anyway, using the string.chars protocol.
[5, 6, 7, 3] |> enum.reverse |> enum.join |> string.to_integer by way, can achieve same thing without using strings @ all:
[5, 6, 7, 3] |> enum.reverse |> enum.reduce(0, &(&2 * 10 + &1)) oh, , there's integer.digits , integer.undigits, can used convert integer , list of digits. it's not present in current release, though in 1.1.0-dev branch suspect come in 1.1.0. can watch progress here.
[5, 6, 7, 3] |> enum.reverse |> integer.undigits
Comments
Post a Comment