I've been learning Elixir for awhile now but I came across something today that totally confused me.
I made this filtering function:
thingy = for a <- ["may", "lay", "45", "67", "bay", "34"], do: Integer.parse(a)
for {n, _} <- thingy, do: n
output: '-C"'
Completely unexpected output, yet the version below 'works'
parseds = for i <- [ "10", "hot dogs", "20" ], do: Integer.parse(i)
for {n, _} <- parseds, do: n
output: [10, 20]
However if I change the numbers to something like 45 and 65 I get '-A'
as the result.
Is this just the underlying binary functions permitting me from using which numbers I like?
This is because Elixir, like Erlang, doesn't internally have a String type. Single-quoted strings are represented as character lists, and these are commonly used when dealing with Erlang libraries. When you give Elixir the list
[45, 67, 34]
, it displays it as a list of ASCII characters 46, 67, and 34; which are-
,C
, and"
.If at least one number in your list doesn't represent a printable character, you see the list of numbers. Because
10
doesn't map to a printable character, in the second example, you see10
and20
.It's important to note that the list you've created is still internally represented as
[45, 67, 34]
so any list operations you do will work exactly as you'd expect with your numbers.