Elixir – Char lists

  • Post author:
  • Post category:Elixir
  • Post comments:1 Comment
Elixir - Char lists

This topic is about Elixir – Char lists.

A char list is nothing more than a list of characters. Consider the following program to understand the same.

IO.puts('Hello')
IO.puts(is_list('Hello'))

The above program generates the following result −

Hello
true

Instead of containing bytes, a char list contains the code points of the characters between single-quotes. So while the double-quotes represent a string (i.e. a binary), singlequotes represent a char list (i.e. a list). Note that IEx will generate only code points as output if any of the chars is outside the ASCII range.

Char lists are used mostly when interfacing with Erlang, in particular old libraries that do not accept binaries as arguments. You can convert a char list to a string and back by using the to_string(char_list) and to_char_list(string) functions −

IO.puts(is_list(to_char_list("hełło")))
IO.puts(is_binary(to_string ('hełło')))

The above program generates the following result −

true
true

NOTE − The functions to_string and to_char_list are polymorphic, i.e., they can take multiple types of input like atoms, integers and convert them to strings and char lists respectively.

In this topic we learned about Elixir – Char lists. To know more, Click Here.

This Post Has One Comment

Leave a Reply