elbasti
Why does String.to_integer/1 give strange results with with some values?
Hi folks, I’ve been running into some very strange behavior that has me knocking my head against the wall.
If I run the following code:
["42", "12", "15"]
|> Enum.map(&(String.to_integer(&1)))
I get what you’d expect: the list [42, 12, 15]
But if I run this code:
["41", "92", "73", "84", "69"]
|> Enum.map(&(String.to_integer(&1)))
I get this weird string: ~c")\\ITE"
In fact, if I run just this:
["41"]
|> Enum.map(&(String.to_integer(&1)))
I get ~c")"
What on earth is going on?!
I figured “maybe there’s some unicode strageness going on with LiveBook” so I tried it in iex, with the same results:
Most Liked
outlog
congrats on reaching this milestone - and completing a major step/rite of passage on your elixir journey - it’s a charlist Binaries, strings, and charlists — Elixir v1.21.0-dev
we have all been there - and gone through the same wtf etc.
dimitarvp
Yeah, you are basically seeing the runtime trying to be a bit too helpful – if a list of integers looks like a list of printable characters, then the REPL will instead show them as a printable string. The data is still there and is still the same.
If you want to get rid of that behavior in your project, just create an .iex.exs file at the root of your project and put this in there:
IEx.configure(inspect: [charlists: :as_lists])
Restart your iex session and, et voila:
iex(1)> ["41"] |> Enum.map(&String.to_integer/1)
[41]
LostKobrakai
I think that would just surface how often we actually run into charlists when interacting with erlang libraries. E.g. hardly any elixir app doesn‘t use gen_tcp somewhere.
From my personal experience I‘ve been hitting the case of needing to see the underlying list of integers mostly in tests or puzzles, where there is time and opportunity to deal with the printed formatting. Not optimal, but fine.
Interacting with actual charlists on the other hand comes up when you‘re debugging some production issue and trying to dig deeper into some failure, where you don‘t want to deal with first setting up useful formatting rules to be able to understand what the system is trying to provide in information.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance










