Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "?\s" mean in Elixir?

In the Elixir-documentation covering comprehensions I ran across the following example:

iex> for <<c <- " hello world ">>, c != ?\s, into: "", do: <<c>>
"helloworld"

I sort of understand the whole expression now, but I can't figure out what the "?\s" means. I know that it somehow matches and thus filters out the spaces, but that's where my understanding ends.

Edit: I have now figured out that it resolves to 32, which is the character code of a space, but I still don't know why.

like image 635
xeruf Avatar asked Aug 02 '26 19:08

xeruf


1 Answers

erlang has char literals denoted by a dollar sign.

Erlang/OTP 22 [erts-10.6.1] [...]

Eshell V10.6.1  (abort with ^G)
1> $\s == 32.
%%⇒ true

The same way elixir has char literals that according to the code documentation act exactly as erlang char literals:

This is exactly what Erlang does with Erlang char literals ($a).


Basically, ?\s is exactly the same as (question mark followed by a space.)

#               ⇓ space here
iex|1 ▶ ?\s == ? 
warning: found ? followed by code point 0x20 (space), please use ?\s instead

There is nothing special with ?\s, as you might see:

for <<c <- " hello world ">>, c != ?o, into: "", do: <<c>> 
#⇒ " hell wrld "

Also, ruby as well uses ?c notation for char literals:

main> ?\s == ' '
#⇒ true
like image 191
Aleksei Matiushkin Avatar answered Aug 08 '26 11:08

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!