1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Append To A Keyword List as an elixir til

Add a new Elixir section too
This commit is contained in:
jbranchaud
2016-02-11 08:40:18 -06:00
parent c42c698947
commit 25079085db
2 changed files with 48 additions and 1 deletions

View File

@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
warrant a full blog post. These are mostly things I learn by pairing with
smart people at [Hashrocket](http://hashrocket.com/).
_329 TILs and counting..._
_330 TILs and counting..._
---
@@ -15,6 +15,7 @@ _329 TILs and counting..._
* [Clojure](#clojure)
* [Devops](#devops)
* [Elixir](#elixir)
* [Git](#git)
* [Go](#go)
* [JavaScript](#javascript)
@@ -62,6 +63,10 @@ _329 TILs and counting..._
- [Running Out Of inode Space](devops/running-out-of-inode-space.md)
- [Wipe A Heroku Postgres Database](devops/wipe-a-heroku-postgres-database.md)
### Elixir
- [Append To A Keyword List](elixir/append-to-a-keyword-list.md)
### Git
- [Accessing a Lost Commit](git/accessing-a-lost-commit.md)

View File

@@ -0,0 +1,42 @@
# Append To A Keyword List
If you have two keyword lists, you can append them like so:
```elixir
> a = [a: 1]
[a: 1]
> b = [b: 2]
[b: 2]
> a ++ b
[a: 1, b: 2]
```
But what if something a bit more programmatic is happening and you are
building up the additions to the keyword list based on variables?
```elixir
> x = :x
:x
> c = a ++ [x 5]
** (CompileError) iex:5: undefined function x/1
(stdlib) lists.erl:1353: :lists.mapfoldl/3
(stdlib) lists.erl:1354: :lists.mapfoldl/3
```
That makes elixir think `x` is some function when in fact it is just a
variable containing the keyword `:x`.
Simply adding a comma doesn't quite do it either.
```elixir
> c = a ++ [x, 5]
[{:a, 1}, :x, 5]
```
We need to wrap the internal part with curly braces to create the tuple that
can then be appended to `a`.
```elixir
> c = a ++ [{x, 5}]
[a: 1, x: 5]
```