Need some help on Elixir Lists

iex
Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Interactive Elixir (1.2.3) - press Ctrl+C to exit (type h() ENTER for help)

List substraction

iex(10)> [12,2]–[2,3,4,5,6]
‘\f’

I was expecting answer 12, how is ‘\f’ is displayed? Also I was expecting a list but got string.

When I have the list with [1,2] and try to perform below subtraction I get expected answer [1]
iex(11)> [1,2]–[2,3,4,5,6]
[1]

Same concern I have here:
iex(12)> [13,2]–[2,3,4,5,6]
‘\r’
iex(13)> [10,2]–[2,3,4,5,6]
‘\n’

This should help: http://stackoverflow.com/questions/30037914/elixir-lists-interpreted-as-char-lists
And this: http://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html

1 Like

Those links should help you out.
One important point is that ‘\f’ is not a string. It’s a charlist (single quotes for charlists and double quotes for strings), and the behavior of charlists and strings are totally different.

This comes up often and it’s just one of those quirks that you have to get used to. I find it helpful when in an iex session to type

iex> ?\f
12

As above, single quotes = list of characters. Dave Thomas’ book primed me wel for this idiosyncrasy.

M

2 Likes

The i command in iex was written to help with this exact problem.

iex(1)> [12,2]–[2,3,4,5,6]
‘\f’
iex(2)> i v(1)
Term
‘\f’
Data type
List
Description
This is a list of integers that is printed as a sequence of characters
delimited by single quotes because all the integers in it represent valid
ASCII characters. Conventionally, such lists of integers are referred to as
“charlists” (more precisely, a charlist is a list of Unicode codepoints,
and ASCII is a subset of Unicode).
Raw representation
[12]
Reference modules
List

2 Likes