AddThis

Tuesday, July 2, 2013

Dave Thomas Recap and Elixir Intro

Just wanted to follow up with my talk with Dave Thomas and various other fun speakers.  Dave didn't speak for very long, but the little he did was very impressive.  Let's just get right into it.  Dave talked about Elixir, which as you already know from my last post is a Ruby like syntactical language that runs on the Erlang VM.  Now the ErlangVM is dang cool, and for more information, read my last post :)

So pretty syntax?  That's it??  Well, there is quite a bit of power in more than just the syntax, but I'm not ready to go into all that yet in this post.  I'm here just to talk about the pretty syntax.  How pretty you might ask?  Let's say you wanted to solve the infamous Fibonacci series.  Everyone's done this.  The concise way is typically to use two methods, one that you call recursively to build your result.  And then you're a clever person so you do some sort of memoization or dynamic programming approach.  Yay (I'll probably post more about these approaches later, but for now, just wiki them)!  Well throw all that stuff out and check out the Elixir approach:


defmodule Cool do
  def fib(0) { 0 }
  def fib(1) { 1 }
  def fib(n) { fib(n-1) + fib(n-2) }
end

IO.puts Cool.fib(10)


Ok what???  Yes, that's the program.  It looks like all I did was describe the problem, there's no way that's actual runnable code.  But it is.  Taking from the Erlang gentle intro from last post, every bit of code is name spaced, or in some sort of class type object, or in Erlang, a module.  We simply describe the problem:

If we pass in 0, we want 0.
If we pass in 1, we want 1.
If we pass in anything else, we want that thing called using this statement but subtracting one and then added to the same but substracting two.

Ok not as concise as the mathmatical symbols, but you get the idea.  We describe the problem and bam!  It just works.  This works because of an Erlang construct known as pattern matching.  It's really not that complex.  So if we call

Cool.fib(1)

This method matches the second of the equations up there, b/c the argument is 1.  If we call

Cool.fib(0)

it matches the first equation (function) because the argument here is 0.  And if we pass something that's not 1 or 0, that falls into n which then calls the third function.   Which as you can see, will cause a recursive call.  Pattern matching is awesome and allows us to define the problem in terms of equations instead of if/else's.  Dave boasts that using this, you can write a whole program devoid of any if/else branching.  He also quickly created a program that spawned multiple processes and had them all work in parallel to compute some result.  I'm not going to get into that now, but just now that it's out there.  I think the best take away I had from his talk was his last quote:

"If you aren't writing functional code in the next few years, you'll be writing maintenance code."


Post a Comment