# Pattern Matching In Elixir

This post can be found on the Quick Left blog.

## Introduction

Learning a new language is a great way to expand your knowledge about programming. You’ll usually pick up some cool tricks or a new way of thinking about things. One of the things I’ve learned that’s different about Elixir is pattern matching. It comes from its Erlang roots and it seems like one of those things that I’ll wish every other language had from now on.

## What Is Pattern Matching?

In Elixir, the `=` sign doesn’t necessarily mean “set this variable equal to something else”. Instead, it means “match the left hand side to the right hand side”. Usually you can declare things like `x = 2` and never notice a difference. At some point though, you’ll start to notice something is quite a bit different.

``````iex> x = 2
2
iex> y = 3
3
iex> 2 = x
2 # waaaat?
iex> 2 = y
** (MatchError) no match of right hand side value: 3
``````

No, `2` is not being set equal to `x`. It’s being pattern matched against it! The difference is subtle now, but let’s go on to see how useful it can be.

### A Note About Immutable Variables

Elixir is a functional language which means that variables can’t change value. You can, however, reuse variable names. If you set `x = 2` and then set `x = 3`, Elixir doesn’t mind.

``````iex> x = 2
2
iex> y = 3
3
iex> x = y
3
iex> x
3
iex> ^x = 2 # force no reusing of variables
** (MatchError) no match of right hand side value: 2
``````

Behind the scenes, though, there’s still a version of `x` that is set to `2`. For instance, if you pass `x` to another function that’s being run concurrently and then change `x`, the concurrent function will still have the original value of `x`. You can force variables to not be reused by using `^`, but `^x = 3` would still match because `x` actually is `3`.

## Basic Pattern Matching

Let’s say you have a tuple and want to assign its different values to some variables.

``````iex> {result, value} = {:ok, 2}
{:ok, 2}
iex> result
:ok
iex> value
2
``````

Cool. We can pick up the different values and assign them to variables. But what if we only want to assign `value` if the result is `:ok`?

``````iex> {:ok, value} = {:ok, 2}
{:ok, 2} # this passed the pattern match
iex> value
2
iex> {:ok, value} = {:nope, 2}
** (MatchError) no match of right hand side value: {:nope, 2}
``````

This actually matches the `:ok` from the left hand side to the right hand side. `value` only gets assigned because the entire tuple (including the `:ok`) matches. The second one doesn’t match because `:ok` is not `:nope`. Again, this might seem pretty useless, but look at how we can use this in real code:

``````# my_case.exs
defmodule MyCase do

def do_something(tuple) do
case tuple do
{:ok, value} ->
"The status was :ok!"
{:nope, value} ->
"Nope nope nope nope..."
_ ->
"You passed in something else."
end
end

end
``````

Then load up the file in `iex` by running `\$ iex my_case.exs`.

``````iex> MyCase.do_something({:ok, true})
"The status was :ok!"
iex> MyCase.do_something({:nope, true})
"Nope nope nope nope..."
iex> MyCase.do_something({:wat, true})
"You passed in something else."
``````

I hope it’s becomming apparent that pattern matching is a useful tool in Elixir. If you use it right this can help make your code easier to read.

## Pattern Matching In Function Definitions

This is where pattern matching truly shines and you’ll use it all the time in Elixir. You can declare functions that will only be executed if the arguments match the patterns. Let’s take a look.

``````# talker.exs
defmodule Talker

def say_hello(:bob), do: "Hello, Bob!"
def say_hello(:jane), do: "Hi there, Jane!"
def say_hello(name) do # name is a variable that gets assigned
"Whatever, #{name}."
end

end
``````

Then load up the file in `iex` by running `\$ iex talker.exs`.

``````iex> Talker.say_hello(:jane)
"Hi there, Jane!"
iex> Talker.say_hello(:bob)
"Hello, Bob!"
iex> Talker.say_hello("Trace")
"Whatever, Trace."
``````

As you can see, three different methods are actually called based on what’s passed into them! This is laying the foundation for doing some really awesome things. Recursion in Elixir, for example, relies heavily on pattern matching. Let’s take a look.

## Uses In Recursion

Let’s define a function that will recursively square every number in a list. We start by defining the base case which is when we pass in an empty list `[]`. Then we define the function that actually does the squaring.

``````# my_squarer.exs
defmodule MySquarer do

def square([]), do: []
end

end
``````

In Elixir, you can express a list as the first component (the head) and then the rest of the list. The last element is always an empty list. So when we say `[head | tail]`, we are quite literally matching the first item in the list to `head` and the rest of the list to `tail`.

``````# example showing what head and tail are
iex> [head | tail] = [1, 2, 3, 4]
[1, 2, 3, 4]
1
iex> tail
[2, 3, 4]
iex> [head | tail] = [1]
[1]
1
iex> tail
[]
``````

So back to our `square/1` function. It returns a new list with the squared `head` as its first element and recursively calls `square/1` to fill in the rest of the list. After the last element is reached, the function definintion `square([])` will match an empty list and return an empty list. That’s when the function call chain will complete and return the result.

Let’s see this in action. Load up the file in `iex` by running `\$ iex my_squarer.exs`.

``````iex> MySquarer.square([])
[]
iex> MySquarer.square([1, 2, 3])
[1, 4, 9]
iex> MySquarer.square([-1, -2, -3])
[1, 4, 9]
``````

## Wrap Up

Hopefully you now have a clearer understanding of what pattern matching in Elixir means and how it can be useful. Recursion is tricky but Elixir’s pattern matching helps us to make it a little easier to read and understand.

If you have any questions, leave them in the comments!

# Lightning Fast Elixir

I have this arbitrary career goal: I want to make a back end that serves millions of requests and does it blazingly fast. Having been a Rails developer for most of my programming career, I’ve been branching out to learn a new language. As you can see from my past posts, I was dabbling with Golang. I even wrote http://gruuub.com with it. It’s fast for sure, but I wanted to see what else was out there.

Enter Elixir and Phoenix. Elixir is a new language built off of Erlang. Phoenix is a web framework for Elixir. And it’s fast. Lighting fast. Serve pages in microseconds fast.

## First Impressions

Functional programming is weird. I tried to do an exercism.io in Elixir and utterly failed. After that, I decided that some reading was in order. I bought Programming Elixir and started reading it, and that helped a ton. I could actually write some Elixir code after that. Nice. On to making a web app!

Phoenix is an MVC framework heavily inspired by Rails. In fact, I found that a lot of features of Rails are already present in Phoenix. Migrations, the awesome router we all know and love (albeit slightly different), even the flash. It’s a full-featured web framework for sure. Getting it up and running equally simple. Install Elixir, install Phoenix, generate an app, create your database, and run `mix phoenix.server`. Pretty simple.

## A Test Drive

After I commited to a hack-a-thon that Quick Left (my employer) was hosting, I decided to use Phoenix for the back end of my team’s web app. Why not? I had yet to use it for something real and I didn’t really care about winning. So I used it. The result? I was surprisingly productive. We only had about 2 - 3 hours to write something. In that time, I spun up a web server with a couple JSON API endpoints that served (mocked) data for the JavaScript front-end.

I tried utilizing the database, but failed. I created 3 models with migrations, but ultimately failed to implement the controller actions for them correctly, so I scrapped it and just used mock data. But holy Batman, making those models and migrations was dead-simple because of the generators.

## Speed

If I were 1) using the database and 2) serving from a real server (not localhost), I’m guessing this would be slower. But I don’t think it would slow down that much. Here’s the server log with response times:

Behold, MICROSECONDS. Have you ever seen that `µ` symbol in a server log before? My team mate had to Google it. Yeah…lightning fast.

## TL;DR

Phoenix is lighting fast but is still just as productive as Rails. More to come when I get something working in production. You should also hire QuickLeft to make something with Elixir so I can get paid to work with it more.

# Positive Pressure

As a brief follow-up to my last post, Learning to Program, I thought I’d write about the benefits of positive pressure for learning.

If you’re like me, you’re a busy person. You work full time, have hobbies that aren’t programming, and maybe have pets or kids that depend on you. On top of that, you still have to do the necessary things like cook, do laundry, mow the yard, and clean the house. Finding time to work on learning a new skill can be hard.

For me, one of the best things to force myself to learn is to commit to something. A week ago I committed to speaking at the Boulder Gophers Meetup group. Despite my last post giving the impression that I’m some Go expert, I hadn’t yet written a non-trivial Go application. What did I commit to talk about? Consuming APIs in Go. Not very light material. Not very trivial. Let the pressure begin!

By committing to something like this, you’re forcing yourself to step up. You may feel like dropping out and making excuses for why you can’t deliver on your promise, but don’t. You’re a smart person. You can figure it out. The benefit to this is that you’ll actually come out having accomplished something. You’ll want to do a great job and therefore you’ll work hard on it, much harder than if it was just something you were toying with in your free time.

In this way, pressure can be a positive thing. Embrace it and let it work in your favor. Even if things go terribly wrong, you’ll feel better because you had the guts to make yourself vulnerable and try something challenging.

# Learning to Program

If you're learning to program, you should be programming. - Alex Allain

Recently I’ve been learning Golang. It’s a cool little language, seems very powerful, but I haven’t used it in production yet. There’s something about learning a new technology that just seems to push you. Learning how to do things in other languages, or even in the same language but a different way, broadens your horizons and adds another tool to your toolbelt. (Besides your golden hammer, which is the best tool ever.)

That being said, if you’re learning to program, you should be programming. I remember when I first started learning to code, my biggest problem was figuring out what the hell to use all of this stuff for: what can I make? The answer: quite a lot, quite a lot.

For starters, you should probably make a hello world and just make sure the language is set up correctly. After that, it makes a lot of sense to start with small projects, like a FizzBuzz type of program. Then just make things progressively harder and larger. The key is to keep pushing yourself.

## Exercise Yourself

One of the best tools I’ve found for this is exercism.io. It basically walks you through practice problems, which usually increase in difficulty. It also adds a whole social dynamic to learning to program. People can review your solutions and critique them. Woot! I’m a huge fan of constructive criticism, and you should be too. It’s not scary, it helps you get better. Sometimes it hurts your ego, but just realize that other people are trying to help you. (Whatever happens, the world will go on.)

## Making It Real

These practice problems are awesome for beginning to learn a language, but you eventually need to go even further and build an application (assuming that’s what you’re learning the language for). Make something big. Here are some ideas:

• A blog
• A personal website (if it’s a web technology)
• A wiki
• An API that does something (mildly) useful
• A multiple-person chat room (oooh, things are getting juicy)
• Something that keeps track of books you have and haven’t read and emails you suggestions
• A note taking app

In short, just think of something that sounds fun, sounds similar what your goal for learning the language is (i.e. easier versions of future programs you want to write), and doesn’t sound too hard. You’re a programmer and the technology playing field is constantly moving. You’ve got to push yourself to keep up. You don’t want to be the guy who goes into an interview and can’t write a program.

# Disposable Employees

Train people like you want them to leave and treat them like you don't.

That was what my step-father said when I told him why I accepted a job at a new company.

Very prudent advice, but in an economy where employees can be a dime a dozen that advice apparently doesn’t hit home with employers. Sure, there are always going to be jobs with a high turnover rate that are easy enough to train for, but for the most part keeping your existing employees means keeping hard to replace knowledge and expertise.

Think of your average employee’s first week. How productive are they, truly? What about their first month? How long does it take to get them acclimated to your company’s business needs, culture, or hell, even special lingo. How long does it take them to form bonds with their co-workers that help them become a great team?

I have to admit, I don’t know how many companies actually treat their employees as disposable. Having been at one that does, however, was enough for me to realize why I’d never want to work at another one.

If I ever own a company, I’m going to train the hell out of my employees, treat them like they’re family, pay them more than market value, and listen when they come telling me things that are hard to hear. It will probably be expensive, sure, but can you put a price on your company’s life-blood not secretly wishing they were working somewhere else?

# Using attr_accessor with attr_accessible in Rails

I’ve found using `attr_accessor` on Rails projects is a stumbling block for many developers. We’ve been using `attr_accessible` our entire Rails career, but then we jump on a project and see `attr_accessor` defined in a Rails model. What the …? In this post we’ll talk about how to use `attr_accessor` with Rails’ `attr_accessible`, where it can be useful, and things to watch out for.

## attr_accessor

Plain and simple, `attr_accessor` is a plain old Ruby way to define getter and setter methods. It’s essentially `attr_reader` and `attr_writer` combined. Specifically:

Again, `attr_reader` only defines the getter, the `content` method in this case, and `attr_writer` only defines the setter, the `content=` method. `attr_accessor` defines them both. And an instance variable. Woot!

This is great for setting instance variables on objects in Rails that you don’t plan on persisting.

## attr_accessible

(Warning, this applies to Rails 3.2. I’m pretty sure this changes because of strong parameters in Rails 4+, but I’m not exactly sure how. Updates to come.)

We all know and love `attr_accessible`, but what does it do? In Rails 3.2, it’s very similar to `attr_accessor` as it defines getters and setters, but it also lets you mass assign attributes. What does that mean? It simply means you can update multiple attributes at the same time, like you would with a params hash from within a controller. An example:

When you specify `attr_accessible`, Rails assumes that this attribute has a corresponding column in your database, and defaults to saving it there. This means that your Post class tries to save the content attribute in `posts.content` in your database. Makes sense.

## Combining The Two

When you define `attr_accessor` with `attr_accessible` on the same attribute, you are telling Rails a couple things. First, you want to be able to mass assign this attribute. Second, that you don’t want to persist this attribute in the database, but store it in an instance variable instead. This can be useful for dictating logic in your model, like so:

In this example, the Post class will immediately publish this post upon creation. The attribute `publish_immediately` would perhaps represent a checkbox on the create post form. Assuming we don’t want to persist this, the previous code block would let us store the value of the checkbox in an instance variable, which we access on the `after_create` line. Again, `attr_accessor` intercepts Rails’ attempt to store the attribute in the database, and stores it in an instance variable instead.

## Closing Thoughts

There are probably situations where this would come in handy, but my personal recommendation is to go ahead and persist your attributes. Database storage is cheap and you never know when your boss (or customer) will come to you and say, “Hey, was that one post published immediately?”.

# My Migration Only Works The Second Time

You want to write a Rails 3.2 migration that also transforms some data, you say? You might want to try something like this:

And you would think this is correct. It looks very correct, indeed. But let’s suppose you run a migration AFTER this one that uses the is_banana column you added. Perhaps something like this:

If you run these two migrations at the same time, the second one will fail saying `unknown attribute is_banana`. If you run it a second time, it will succeed.

## Why?

Rails keeps a cache of which tables have which columns, something that gets updated when you add a column in a migration. Furthermore, it seems like having the line

prevents Rails from immediately updating the cache of columns on that table.

So when we go to update that model in the next migration, Rails thinks the `is_banana` column doesn’t exist, giving you an `unknown attribute is_banana` error. When you run the migration a second time, Rails gets a chance to update the cache and it succeeds.

To fix it, we can use the method `reset_column_information`. Let’s see it in use:

# Coming Along

Ahhh, a functioning website. One that doesn’t look completely terrible even! (OK, don’t crush my hopes and dreams just yet.) As detailed in the last post, I recently converted my site to use Jekyll instead of WordPress.

I’ve heard WordPress get a little bit of hate from a couple of programmers I’ve talked to, which at times can be understandable. Mostly, though, WordPress is awesome. For me, it was a little too heavy. I don’t really need the database for anything. I’m writing the code from scratch (mostly to learn). Plus, static sites are WAY cheaper to host (thanks Amazon S3).

## How’s It Done?

Jekyll is a Ruby-based blog that generates static HTML for you to upload to your server. “Templates” are written in HTML and each blog post is written in Markdown. Since the entire site is plain ‘ole HTML, you can host it just about anywhere. I have found that Amazon S3 is very cheap, and I pay about \$0.50 per month to host this site.

Having to deploy the entire site each time is a bit of a hassle, but I’ve written a nice little Rake task to do it for me.

Now I can simply type `rake deploy` and the site gets pushed live. The old version of the site is even backed up!

# Website Changes

Hello, world! I’m in the process of changing my website. I’m switching from a WordPress based site to a Jekyll powered static site, so there is a bit of a learning curve to get it up and running. I hope to have it done soon though! Expect to see periodic changes when coming here.