Functional programming languages are at full throttle right now, thanks to multi-core processors and concurrency. The industry experts are frowning upon writing mutable code and functions have replaced the once popular objects as first class citizens. There are a number of functional languages like Scala, Clojure, Haskell, Erlang and the list goes on. In the first part of the series of articles on functional programming languages, I will introduce you to a language called Elixir.
We have JVM based functional languages like Scala and Clojure. Elixir is based on Erlang Virtual Machine (EVM). Erlang is a popular functional language that gets compiled and executed on EVM. The Elixir code that we write also gets executed on the EVM. Elixir is semantically very similar to Erlang, but more expressive and has a larger feature set.
In this article, we will set up the Elixir Environment and look at some features like immutability and pattern matching and we will wind up with a simple exercise.
Taking the first step
Getting started with Elixir is easy. You can install Elixir by using homebrew.
brew install Elixir
Homebrew installs Elixir and the pre-requisites, mainly Erlang.
Elixir gives you an interactive console iex. Let’s print Hello World in iex as shown here.
But that’s too simple. Let’s write our code in a file, compile it using elixirc and then run it. Elixir code spans over modules. A module is like a container that’s composed of functions. Let’s define a simple module in Elixir, add some functions to it and invoke them. We’ll create a file hello_world.ex and define a +HelloWorld* module in it.
defmodule HelloWorld do def hello do IO.puts "Hello World" end end
Let’s compile hello_world.ex using elixirc. When you do that, you get a Elixir.HelloWorld.beam file as shown below. The beam file contains the bytecodes that get executed in the EVM.
You can start the interactive console again and run the HelloWorld.hello function as shown below.
We can create Elixir scripts and directly execute them instead of compiling it and invoking it from the console. All we need to do is name the Elixir code file with a .exs extension and run it using elixir. Let’s define HelloWorld module in hello_world.exs file.
#hello_world.exs defmodule HelloWorld do def hello do IO.puts "Hello World" end end HelloWorld.hello
Execute the script from the console(not from iex) as shown here.
Alright!! Let’s crack some more code in the next part.