Dive into ErLang

I recently had a chance to learn Erlang. In the beginning, it was quite hard to find a good book or tutorial that gave a clear idea of the language and the best practices. Hoping this blog can help someone who wants to get started.

As I began, it started to strike me that modern languages like Go, Ruby, Javascript have parts which have some similarity with Erlang. The parts include concurrency aspects w.r.t. passing messages using channels in Golang, the way functions  return results of last executed expression in Ruby and first class functions in Golang/Javascript.

Erlang’s history revolves around telecom industry. It has been known for concurrency using light-weight processes, fault-tolerance, hot loading of code in production environments etc. The Open Telecom Platform (OTP) is another key aspect of Erlang which provides the framework for distributed computing and all other aspects mentioned above.

Some key points to keep in mind,

  • Values are immutable
  • Assignment operator (=) and functions work based on pattern matching
  • No iterative statements like for, while, do..while.. etc. recursive functions serve the purpose
  • Lists, Tuples (records – a hack using tuples) are very important data structures
  • If, Case.. Of.. are the conditional blocks
  • Guards are additional pattern matching clauses used with functions and Case.. Of..
  • Every expression should return a value and last expression in a function automatically returns the result
  • Functions are first class citizens
  • Usage of punctuations ‘; , .’ etc. (one can relate this to indentation requirements in python)

Lets gets started with some code samples,

% Execute this from erlang shell. erl is the command
> N = 10.
%% The above statement compares N with 10 and binds N with 10 if its unbound. If its already bound with some other value, exception is thrown.

%% Tuple
> Point = {5, 6}

%% List
> L = [2, 5, 6, 7].
[2, 5, 6, 7]

%% Extracting Head and Tail from List is key for List processing/transformations
> [H|T] = [2, 5, 6, 7].
[5, 6, 7]

%% List comprehensions
> Even = [E || E <- L, E rem 2 =:= 0].

Lets take a look at the simple functions,

helloworld () -> hello_world.

The simple function will return hello_world, a constant string – atom. Lets have a look at a recursive function,

%% Factorial of N
factorial (N) when N =:= 0 -> 1;
factorial (N) -> N * factorial(N-1).

%% Tail recursion
tail_factorial (N) -> tail_factorial(N, 1).
tail_factorial (0, Acc) -> Acc;
tail_factorial (N, Acc) -> tail_factorial (N-1, Acc * N).

The factorial functions demonstrate how Erlang does pattern matching on function parameters, usage of  Guard (‘when’ clause), punctuations. We could have also written the statement as ‘factorial(0) -> 1;’ .

The second version tail_factorial demonstrates the optimized version using tail recursion to simulate the iterative method. In this method Erlang would remove the previous stack frames using Last Call Optimization (LCO). It is important to understand both techniques as recursion is used quite extensively.

Erlang has the following data types – atom, number, boolean (based on atom), strings and binary data. atom’s occupy more space and its better to using binary data type for strings of larger sizes.

Other builtin data structures are queues, ordsets, sets, gb_trees . Error, Throw, Exit, Try.. Of .. Catch statements provide the exception handling capabilities.

The most interesting part of the language is about spawning light weight processes and passing messages between them,

– module (dolphin-server).
%% API
– export ([dolphin_handler/0]).
dolphin_handler() ->
         do_a_flip ->
               io:format (“How about no ? ~n”);
          fish ->
io:format (“So long and thanks for the fish! ~n”);
          _ ->
               io:format (“we’re smarter than you humans 😉 ~n”);
%% From shell, compile dolphin-server module


%% Spawns a new process
> Dolphin = spawn (‘dolphin-server’, dolphin_handler, []).

<0.124.0> %% process id of the newly spawned process

%% Now start passing messages!!

> Dolphin ! fish.
So long and thanks for the fish!
>Dolphin ! “blah blah”
we’re smarter than you humans 😉
This demonstrates the compilation of dolphin-server module, spawning of the dolphin-server as a separate process and communicating to the process using messages.
Further to passing messages, erlang provides capabilities around linking multiple processes, passing references for reliability, policies around restarting processes as a group/single etc.

Open Telecom Platform (OTP)

While it is interesting to write all the boiler plate code for spawning and communicating with multiple processes, Erlang makes it easy for by providing all these generic pieces of functionality as behaviour modules in OTP framework.
OTP design principles define how to structure Erlang code in the form of processes, modules and directories.
The following are the behavior modules,
  • gen_server – for implementing server side piece in client/server
  • supervisor – for implementing a supervisor in a supervisor tree. It takes care of the details regarding restarting of processes, fault-tolerance etc.
  • gen_event – for implementing event handling functionality
  • gen_statem – for implementing state machines

https://learnyousomeerlang.com/contents is one of the best online books for understanding how to use Erlang,  best practices while building an application which is production ready.  Its good to take pauses and move with book as its quite exhaustive, but wonderfully written 🙂


Words of silence

When Buddha got enlightened on that full moon day in the month of May, he maintained silence for a whole week. All the angels in the heaven got frightened. They knew that it was only once in a millennium that someone blossoms like Buddha. They requested him to say something. He said, “Those who know, know even without my saying it and those who do not know will not know even by my saying it.”

Buddha said, “Words cannot convey it. As many scriptures in the past have revealed, truth begins where words end.”

The angels said, “What you say is right. But consider those who are in between, who are neither fully enlightened nor totally ignorant. For them, a few words will give a push. For their sake, you speak and every word of yours will create silence.”

The purpose of words is to create silence. If words create more noise, they have not reached their goal.

— from Buddha, Manifestation of Silence
[courtesy – a facebook post from Sri RaviShankar]

A deeper understanding of work and business

This is a little story about how Lord helped me understand why I should be working. There was a period while my relationship with my manager was bad. So the work which I did was not appreciated. It was also evident that I would neither get a good hike nor a good bonus at the end of the year. All my friends including some friends who are in the higher managerial ladder advised me to either switch teams or switch company. With these things rolling in the mind, work at office seemed dull. Every morning as I begin to start to office, above reasoning will go on in the mind and my complete energy would be lost with no answer. SriMurthy Bhagvan makes decisions for me. He, on the contrary to others said me not to change the team. Without knowing why I should work, I could not get on.

One fine morning, I sat before SriMurthy Bhagvan and said that am out of answers. I had thought enough and unable to find an answer why I should be working. It was already a dull period of a week. While I sat blank without answers, suddenly a realization flashed. It said that, I working or business is nothing but people helping each other. Every single person is blessed by the Lord with some skill (through college, courses, individual learning etc.) which may look to be due to his decision or it just happened due to coincidences. But however one might have got this skill, it has come to him beyond his free-will. Businesses, money etc. have been in place to make sure people help each other.
Once this had hit the mind, the work just started to go on. Learning was automatic since, if I do have to help people in a better manner, I better be skilled. While helping people, the smallest thanks for anything I did gave a lot of happiness. While still the relationship with my manager was bad, Bhagvan helped me correct that too explaining me the truth – https://chenthill.wordpress.com/2011/10/20/setting-right-relationships/ . As and when the realization hits, the energy just boosts up. Its all about making people happy by helping each other.

The work at office and the helping people outside remains the same now. The salary, bonus and hike are nothing but a Token of Thanks. Should there be a comparison with each other with Token of thanks, I guess no. If I realize I need a better Token of thanks, I can always ask for it and make decisions without hurting any relationship, for its all about helping people 🙂

Thanks to Lakshmi Prabhaji who urged me to write this down. Hope this might help some people 🙂

Setting right relationships

Without getting into the specfics, am going to share some happenings over the recent past. Don’t ever consider me as an expert or a philosopher. But just a young guy experimenting with what Sri Sri Bhagavan, the Founder of Oneness university taught me. And don’t ever create a image about me by this. If you do not want to read the story, skip to summary. Alright lets get on..

While at work I had been having some issues which prolonged for a long time (3+ years) and finally led me to think strongly about resigning. Last week, due to the love of my mother and SriMurthy Bhagvan who asked me to meet Sri Sri Bhagvan at Oneness, I went there. The conversation lasted for around half an hour. While I said, am going to resign, He said not to resign and asked to set right the relationship on the contrary. He explained in a great deal about the role relationship plays  which was beyond imagination and pit-falls in J Krishnamurthy’s teachings.

I did understand it theoretically but not very much practically. So while coming over in the bus, there were a lot of conversations going on. The thoughts which flowed were trying to find a way to set right the relationship with my boss. There were a lot of justifications and blames. The fluctuations in mental stands were evident and i could not find a way with it. Finding reasons for setting relationship is a play of the mind, which is a result of thinking. Suddenly in the morning, it became crystal clear.

The way was just to set the intent and be in the present. The significant part is not to think or make any effort. Thinking is a vicious circle. It would just justify itself and keep looking right always (at-least for me 😉 ). Being in the present without an intent also does not produce result, i can say this with my experience in cricket.

So intent+awareness=result is the key. Setting the relationship inside oneself leads to joy which is a clear symptom. The outward one will automatically get fixed with intent+awareness.

What Sri Sri Bhagvan explained me was, If the relationship inside is alright, rest of the part, such as job, new house, vehicle, anything etc. will come as a by-product automatically. The relationship got set-right once I came to office and I knew it was fixed even while I started my journey back from oneness university.

He asked me to take one relationship (a close one, eg: mother) and work on all aspects completely. I should remain on the findings, without trying to fix it. Started on it, lets see how it goes 😉

Am certainly very happy to be a part of oneness university 🙂

To summrize:

Intent + awareness = result.

There should not be any reason for enjoying a good relationship with people. For reasons are always bound to change.

SLED Beta call

Last week I attended the sled beta since srini had to go for his visa interview. The call was very informative. Guy gave a talk about the multimedia issues w.r.t licensing/trade-mark/copy-rights which stop us from shipping the windows media decoders in order to play .wma files. He also explained how moonlight will be able to play windows media files. He pointed the customers to get the decoders from fluendo and also mentioned the reason why we don’t ship the decoders in sled getting it from fluendo. He was explaining them very clearly and also conveyed the message about how hard our company is trying to get these issues resolved for the customers. Guy also explained that the other OS such as windows also need third party software for dvd playback which sometimes does not strike me as we get the softwares for windows in a dvd along with the dvd players. It would be great if some steps are taken by the dvd player vendors to include the decoding software for linux too. We did not have much issues for evolution. We had a couple of them which was already mentioned in previous calls and just needed some followup.

Script to generate VCalendar events

Am writing a python script to generate Vcalendar events. The properties such as
summary, description, location etc. are picked up at random if a text
file is given as an input. The appointments would be created between the
range +-6 months from the current time.

Some numbers and the input file are hard coded. The output is written to
a terminal which can be re-directed to a ics file. Will be enhancing it
to add more properties such as attendees, attachments, alarms etc and
read the properties from a spec file soon. Python is awesome !!! Thanks to nags 🙂