Table of Contents
Has this ever happened to you?
iex> IO.inspect([65, 66, 67])
'ABC'
'ABC'
Frustrating, huh? That’s because to Elixir a list of characters (a charlist
) like 'ABC'
is just a list of character codes for those characters: [65, 66, 67]
. This is frustrating when you’re actually trying to deal with a list of integers that happen to be character codes, or to work out what the character codes of a list of characters is.
Passing the charlists: :as_lists
option to IO.inspect/2
will force it to print the underlying list of integers:
iex> IO.inspect([65,66,67], charlists: :as_lists)
[65, 66, 67]
'ABC'
This also works if you pass in a charlist like 'ABC'
. I used this as part of the solution to the RNA transcription Exercism Elixir problem to get the charcodes for the characters that are used for DNA and RNA transcription:
iex> IO.inspect('GCTAU', charlists: :as_lists)
[71, 67, 84, 65, 85]
'GCTAU'