Skip to content

Commit 2507908

Browse files
committed
Add Append To A Keyword List as an elixir til
Add a new Elixir section too
1 parent c42c698 commit 2507908

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,15 @@ variety of languages and technologies. These are things that don't really
77
warrant a full blog post. These are mostly things I learn by pairing with
88
smart people at [Hashrocket](http://hashrocket.com/).
99

10-
_329 TILs and counting..._
10+
_330 TILs and counting..._
1111

1212
---
1313

1414
### Categories
1515

1616
* [Clojure](#clojure)
1717
* [Devops](#devops)
18+
* [Elixir](#elixir)
1819
* [Git](#git)
1920
* [Go](#go)
2021
* [JavaScript](#javascript)
@@ -62,6 +63,10 @@ _329 TILs and counting..._
6263
- [Running Out Of inode Space](devops/running-out-of-inode-space.md)
6364
- [Wipe A Heroku Postgres Database](devops/wipe-a-heroku-postgres-database.md)
6465

66+
### Elixir
67+
68+
- [Append To A Keyword List](elixir/append-to-a-keyword-list.md)
69+
6570
### Git
6671

6772
- [Accessing a Lost Commit](git/accessing-a-lost-commit.md)

elixir/append-to-a-keyword-list.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Append To A Keyword List
2+
3+
If you have two keyword lists, you can append them like so:
4+
5+
```elixir
6+
> a = [a: 1]
7+
[a: 1]
8+
> b = [b: 2]
9+
[b: 2]
10+
> a ++ b
11+
[a: 1, b: 2]
12+
```
13+
14+
But what if something a bit more programmatic is happening and you are
15+
building up the additions to the keyword list based on variables?
16+
17+
```elixir
18+
> x = :x
19+
:x
20+
> c = a ++ [x 5]
21+
** (CompileError) iex:5: undefined function x/1
22+
(stdlib) lists.erl:1353: :lists.mapfoldl/3
23+
(stdlib) lists.erl:1354: :lists.mapfoldl/3
24+
```
25+
26+
That makes elixir think `x` is some function when in fact it is just a
27+
variable containing the keyword `:x`.
28+
29+
Simply adding a comma doesn't quite do it either.
30+
31+
```elixir
32+
> c = a ++ [x, 5]
33+
[{:a, 1}, :x, 5]
34+
```
35+
36+
We need to wrap the internal part with curly braces to create the tuple that
37+
can then be appended to `a`.
38+
39+
```elixir
40+
> c = a ++ [{x, 5}]
41+
[a: 1, x: 5]
42+
```

0 commit comments

Comments
 (0)