>>= Hugo Estrada

Simple quicksort in elixir

I implemented a simple quick sort in elixir to learn about the language.

I have been reading a lot about elixir. Yet no language is learned by reading it. You must do something with it. So to get some concrete learning done, I decided to do a simple implimentation of quicksort using elixir. This is my first script beyond tutorials. Tutorial guide you through ideas and concepts found in the language. Trying to do something by yourself helps to truly learn the concepts.

I started by creating a test. I could have searched for a test library in elixir. Then I would have spent half and hour to an hour doing research. Instead I implemented a very simple function that tests equality. This is all what I need since I am exploring the language.

Now that I had a failing test, I could implement the algorithm. Recently I saw a lighting talk at Ruby Retrocession, organized by Arlington Ruby where they explained how the algorithm works. So with that vague memory in mind, I began my implementation. This is the small script I wrote. Under it I list what I learned from this exercise.

What I learned

All functions must be in modules

This is something of a surprise when you are used to defining stand-alone functions in python or ruby.

How to get head and tail of a list

This was simple. You use pattern matching: [head|tail] = [1,2,3,4].

IO.inspect

I wanted to print the array to confirm its value. I did this with IO.puts, and it didn't work. Since Elixir is influenced by ruby, I searched for inspect. It lovingly lives in IO.inspect(input). This made it ridiculously happy.

The Enum library

The Enum library is where all of functional programming functions for list are located. In this case I wanted to use the filter method. The documentation is excellent.

How to do pattern matching with function definition

We have two syntax shapes for pick from. We can define each function or we can have an aggregate function definition if the base cases return a simple value. Since the aggregate function definition is new to me, I am sharing what it looks like.


            def fn(pattern1), do: 
            def fn(pattern2), do: 
            def fn(pattern3)
                
            end
          
        

How to properly concatenate lists

I kept running into this error where I wanted to join the pivot and the result of the two recursive quick sorts qsort(lower) ++ pivot ++ qsort(higher) The problem here was that pivot wasn't a list. So I had to change it to look like qsort(lower) ++ [pivot] ++ qsort(higher) and make sure that the function definition that matched the empty pivot value returned it as a list, [pivot].

Tags: elixir, quicksort, algorithms