Reputation: 2167
If I have a list like this:
a = [1,2,3]
And second list like this:
b = [4,5,6]
I want these lists to be added like this:
[1,2,3, some_atom:[4,5,6]]
So i want an atom
to in the list like this.
I am trying this:
a ++ [some_atom: b]
Its giving me the output:
[1, 2, 3 {:some_atom, [4, 5, 6]}]
Can any one suggest how can I do that if possible?
Thanks
Upvotes: 3
Views: 84
Reputation: 12157
They are the same thing and work the same way. It is how Keyword lists work.
Try it in iex
:
iex(1)> [foo: "bar"]
[foo: "bar"]
iex(2)> [{:foo, "bar"}]
[foo: "bar"]
Cool right?, Check it.
iex> [foo: "bar", baz: "bar"] == [{:foo, "bar"}, {:baz, "bar"}]
true
And your example:
iex> [1, 2, 3, some_atom: [4, 5, 6]] == [1, 2, 3, {:some_atom, [4, 5, 6]}]
true
Upvotes: 1
Reputation: 8898
As long as you notice that [1,2,3, some_atom: [4,5,6]]
is equivalent to [1,2,3, {:some_atom, [4,5,6]}]
, you should be able to figure out the answer yourself. And your original approach is correct. You can prove it by
a = [1,2,3]
b = [4,5,6]
c = a ++ [some_atom: b]
[1,2,3, some_atom:[4,5,6]] = c # pattern matching passes
Upvotes: 1
Reputation: 10061
What you are getting is the proper result. In Elixir, a Keyword list is just a list of tuples. So,
[key: :value, other_key: :other_value]
is the same as
[{:key, :value}, {:other_key, :other_value}]
In fact, the first is just syntactic sugar for the second.
Upvotes: 1