Tuesday, January 31, 2017

Elixir - Char lists

A char list is nothing more than a list of characters. For example:
IO.puts('Hello')
IO.puts(is_list('Hello'))
When running above program, it produces following result:

Hello
true
Instead of containing bytes, a char list contains the code points of the characters between single-quotes. So while double-quotes represent a string (i.e. a binary), single-quotes represents a char list (i.e. a list). Note that IEx will only output code points 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')))
When running above program, it produces following result:
true
true
NOTE: The functions to_string and to_char_list are polymorphic, ie, they can take multiple types of inputs like atoms, integers and convert them to strings and char lists respectively.

No comments:

Post a Comment