Understanding Charlists

in iex:

| iex > [ ​ 'cat' ​ | ​ 'dog' ​ ]
|> ['cat',100,111,103]

Why does IEx print ’cat’ as a string, but ’dog’ as individual numbers?

Hello,

There are some points to clarify in your code…

  1. ’ is not equal to ", the first define a charlist, the second is a binary
  2. ‘cat’ is a charlist, or a list of char if You prefer… and ‘dog’ is equal to [100, 111, 103]
  3. to get the value of a character, You can use ?, eg. ?a => 97
  4. a list [] is composed by a head and a tail, it is a linked list where head is an element, and tail is a list

What You really wanted is

iex> [?c, ?a, ?t | 'dog']     
'catdog'

# This is also equal to 
iex> [?c | [?a | [?t | 'dog']]]
'catdog'

# it's more common to use binary in Elixir

iex> "cat" <> "dog"
"catdog"

Don’t worry, we all have gone through this :slight_smile:

I recommend this page to dig deeper

1 Like

Because what you have created is list with list as it’s head, this isn’t the same as 'catdog'.

Lets see:

full = 'catdog'
joined = [ 'cat' | 'dog' ]

assert hd(full) == 97
assert hd(joined) == 'cat'

inspect full, charlists: :as_lists
# => [99, 97, 116]
inspect joined, charlists: :as_lists
# => [[99, 97, 116], 100, 111, 103]
3 Likes