Learning Elixir: Part 3

Hi All, Wow, we're already at part 3 and we're barely scratching the surface. I see a long road ahead with so much more learning to do. On the more positive side; I'm getting it and I'm finding it quite enjoyable so far... so let's crack on, shall we?

In the last few days I did two more experiments to do some basic sending and receiving between erlang processes (which I've come to find is a term which is interchangeable with BEAM processes, which is what I really mean).

My first task was to build a function (based on the video I linked to in part 1) that did some distributed work. So for this, I declared a function that took a list and a function and then the function would be applied to each item in the list. This was somewhat similar to a map() function in functional programming. Here's the Elixir part, each function would be run inside it's own Erlang process. Neato.

https://gist.github.com/samjarman/de7dd2337b425d1499cce16d0f1a5831

So, walking through the code, first we make a reference to the process by calling it me. Then on the list, we then map over the list, creating a function that spawns a process, which inside that sends back to the parent process a PID (self) and the result of applying the function to the element. Then on that list of PIDs we receive the result, and presto-we have a list of results. Pretty neat. With the task above, what wouldn't work is if the process was more complex (say, not multiplying a number by itself) and the process was to error out, nothing would rescue that... so that leads me to my next task.

My second task was to start playing with the concept of supervision, a reasonably crucial one in Elixir. I wanted to implement from scratch a really simple supervisor that would look at a randomly failing process and make sure it stayed alive.

https://gist.github.com/samjarman/7043ac55e9518969c8c1839d670d9622

So what I've done here is declared a worker function which fails just a little bit of the time, and if it does, it'll tell it's master about it before exiting. If the master hears about this, it'll respawn it and start listening all over again. Take a read through the code.

My next task is to start implementing some proper Elixir projects. There are also a few good ones to contribute to out there. If you have any suggestions for projects... I'm all ears!

Have you also been learning Elixir or Erlang too? Do you have any tips or comments? Iā€™d love to hear them and share them in an upcoming post. Ping me on twitter.