From 25079085db59127deb6653f974803452f98f243a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 11 Feb 2016 08:40:18 -0600 Subject: [PATCH] Add Append To A Keyword List as an elixir til Add a new Elixir section too --- README.md | 7 ++++- elixir/append-to-a-keyword-list.md | 42 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 elixir/append-to-a-keyword-list.md diff --git a/README.md b/README.md index fa945d4..3f59e67 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/elixir/append-to-a-keyword-list.md b/elixir/append-to-a-keyword-list.md new file mode 100644 index 0000000..a43448b --- /dev/null +++ b/elixir/append-to-a-keyword-list.md @@ -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] +```