Reputation: 43
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?
Upvotes: 0
Views: 112
Reputation: 48629
This is because Elixir, like Erlang, doesn't internally have a String type
Whatever that means. Strings, Smings. It's as simple as:
iex(4)> [45, 67, 34]
'-C"'
In iex, a list of numbers is interpreted as a sequence of characters, where each number is a numerical code for some character. If you look at an ascii chart, you will see that:
45 -> -
67 -> C
34 -> "
Look at this:
iex(5)> 'hi' == [104, 105]
true
In Elixir, [104, 105]
and [45, 67, 34]
are called charlists. A shortcut for creating the charlist [104, 105]
is 'hi'
. This is the result of a terrible feature of Erlang, but because Elixir is able to interface with Erlang, there is a need for charlists. An Elixir charlist is the equivalent of an Erlang string, and an Erlang string is equivalent to a list of numbers.
Suppose your Elixir program does a bunch of critical mathematical calculations with the result being:
result = [76, 64, 78, 79]
and you want to display that info to the user so that they can tune a defibrillator's settings in order to save a patient's life, so you do this:
IO.puts "Set the defibrillator dials to these numbers: #{result}"
Here's what the user will see:
Set the defibrillator dials to these numbers: L@NO
Patient dies here.
Upvotes: 2
Reputation: 15051
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 see 10
and 20
.
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.
Upvotes: 6