Skip to content

Instantly share code, notes, and snippets.

@KronicDeth
Created January 3, 2015 02:07
Show Gist options
  • Save KronicDeth/f17fc29c8f8e44743a7b to your computer and use it in GitHub Desktop.
Save KronicDeth/f17fc29c8f8e44743a7b to your computer and use it in GitHub Desktop.
CharList vs String in quotes and quoted atoms
"'foo\#{'bar'}'" |> Code.string_to_quoted
==
{:ok,
{{:., [line: 1], [String, :to_char_list]}, [line: 1],
[{:<<>>, [line: 1],
["foo",
{:::, [line: 1],
[{{:., [line: 1], [Kernel, :to_string]}, [line: 1], ['bar']},
{:binary, [line: 1], nil}]}]}]}}
":'foo\#{'bar'}'" |> Code.string_to_quoted
==
{:ok,
{{:., [line: 1], [:erlang, :binary_to_atom]}, [line: 1],
[{:<<>>, [line: 1],
["foo",
{:::, [line: 1],
[{{:., [line: 1], [Kernel, :to_string]}, [line: 1], ['bar']},
{:binary, [line: 1], nil}]}]}, :utf8]}}

When using interpolation, inside single quotes, the contents of the Elixir CharList (Erlang string) are internally represented as an Elixir String (Erlang binary) and only become a CharList at the end with a hidden call to String.to_char_list/1 that you can see in the quoted form, so any CharList with interpolation can be written directly as a String.to_char_list(string_with_interpolation) instead for the same quoted form.

When : is added before either the CharList or the String, the quoted form is the same (the only difference is due to the single or double quotes around the interpolated bar). This can be thought of as either (a) quotes for atoms don't have the same meaning as they do normally or (b) when single quotes are used, the String.to_char_list/1 call is stripped when wrapped in the :erlang.binary_to_atom/1 call.

"\"foo\#{\"bar\"}\"" |> Code.string_to_quoted
==
{:ok,
{:<<>>, [line: 1],
["foo",
{:::, [line: 1],
[{{:., [line: 1], [Kernel, :to_string]}, [line: 1], ["bar"]},
{:binary, [line: 1], nil}]}]}}
":\"foo\#{\"bar\"}\"" |> Code.string_to_quoted
==
{:ok,
{{:., [line: 1], [:erlang, :binary_to_atom]}, [line: 1],
[{:<<>>, [line: 1],
["foo",
{:::, [line: 1],
[{{:., [line: 1], [Kernel, :to_string]}, [line: 1], ["bar"]},
{:binary, [line: 1], nil}]}]}, :utf8]}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment