🤔 How to inject a list into a quoted expression
Notes
A couple of tips ago, we saw how to use Elixir’s quote/1
and
unquote/1
to inject values into our quoted expressions.
But how can we inject a list into a quoted expression that has a list while flattening it’s values?
Turns out quote/1
doesn’t quite do the trick:
iex> list = [1, 2, 3]
iex> a = quote do: [unquote(list), 4, 5, 6]
#=> [[1, 2, 3], 4, 5, 6]
That’s disappointing. Isn’t it?
Most of the times we want it to return [1, 2, 3, 4, 5, 6]
.
Thankfully, Elixir has a helper to help us with exactly that problem! It’s
called unquote_splicing/1
:
iex> list = [1, 2, 3]
iex> a = quote do: [unquote_splicing(list), 4, 5, 6]
#=> [1, 2, 3, 4, 5, 6]
That’s more like it!