Freedom_Ben
Freedom_Ben

Reputation: 11943

What does the "?" operator do in Elixir?

The Ecto source code makes use of expressions ?0, ?1, etc. You can see how they evaluate:

iex(14)> ?0
48
iex(15)> ?1
49
iex(16)> ?2
50

What does that mean though? This is very hard to search for. What does the ?<character> actually do?

Upvotes: 2

Views: 544

Answers (1)

Freedom_Ben
Freedom_Ben

Reputation: 11943

From: https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#unicode-and-code-points

In Elixir you can use a ? in front of a character literal to reveal its code point:

If you aren't familiar with code points:

Unicode organizes all of the characters in its repertoire into code charts, and each character is given a unique numerical index. This numerical index is known as a Code Point.

The ?<character> can also be used in interesting ways for pattern matching and guard clauses.

  defp parse_unsigned(<<digit, rest::binary>>) when digit in ?0..?9,
    do: parse_unsigned(rest, false, false, <<digit>>)

  ...

  defp parse_unsigned(<<?., digit, rest::binary>>, false, false, acc) when digit in ?0..?9,
    do: parse_unsigned(rest, true, false, <<acc::binary, ?., digit>>)

The Elixir docs on it also clarify that it is only syntax. As @sabiwara points out:

Those constructs exist only at the syntax level. quote do: ?A just returns 65 and doesn't show any ? operator

As @Everett noted in the comments, there is a helpful package called Xray that provides some handy utility functions to help understand what's happening.

For example Xray.codepoint(some_char) can do what ?<char> does but it works for variables whereas ? only works with literals. Xray.codepoints(some_string) will do the whole string.

Upvotes: 4

Related Questions