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.
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}
{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].
>H.
2
>T.
[5, 6, 7]

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

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() ->
  receive
         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”);
     end,
     dolphin_handler().
%% From shell, compile dolphin-server module

>c(‘dolphin-server’).

%% 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 🙂

Advertisements

Focusing on Solutions

We had a class in oneness university a year back and there was a session on the questions that arise in the mind. Had learnt that quality of questions that arise in the mind affects the quality of life. Contemplating and working on it over a year now, found that some common questions that arise in the mind can be categorized to,

+ Why,  When,  What, How etc.

These questions can lead to focusing on either the problem or solution. Solutions are always Futuristic.

When the questions of Why, What, When etc. comes up  in the mind with a past context,  ‘Why’ more often lead to regret.’Why’ for a happy event that happened in the past does not arise. ‘When’ many a times produced anxiety. ‘What’ though inquisitive was not so powerful.

The question ‘How‘ was so powerful that it changed the whole outlook of thinking. When ‘How’ was placed in the mind, it started making the mind more innovative. The mind was no longer worrying about any problem, but started to produce different solutions. The mind moves into finding out ways to achieve something.  It always gives a good feeling while contributing something very useful to someone.

  • How do I achieve something ?
  • How can I make something exceptional ?
  • How did you do it ?

Learnt that ‘why’ can define a purpose behind  a solution that can draw people to use our products, from a ted talk, “How great Leaders inspire Action“.

 

Centeredness is something I had learnt in recent class. For arriving at a great solution, it is important to ignore our perspectives on something and hear the views from others shoes. This is to be ‘other-centered‘, rather than being ‘self-centered’. I realised this is ‘Art of Listening’.

This is very useful in all cases. Some cases where this has to be present for sure are,

+ While negotiating with someone
+ While dealing with customers/stake holders

One of the highly respected friends who serves in a leadership role in a big company said to me,  ‘I Focus only on Future’. This was implicitly conveying a message that he was always focusing on solutions. While discussing with a senior product manager, he was speaking on the importance of listening from customers view. This implicitly conveyed about ‘other-centeredness’.

Combining the two aspects ‘Asking How’ and ‘Being Other-Centered’ takes the mind to another level which is ‘Focusing on Solutions‘ 🙂

 

 

Polyglot – Learn, Share, Collaborate – Hackfest 2016!!

Polyglot project aims to provide the summary of various choices available for each of the components while developing a web application. It details their strengths so that one can easily choose the right component to build a great solution.

hackfest_2016

I had gone through several blogs, stack-overflow/quora answers to choose a proper database, programming language, web-framework etc. to build a solution in the past. Most of them were out-dated and I had to keep track of the date for each of the posts.

So for this HACKFEST 2016, wondered how would it be if we could share the learning through a wiki and collaboratively maintain an up-to-date content. I had a hunch that this might be a problem that many would have faced and would be good to solve.

It starts with Questions/Concerns one should keep in mind before starting a project. It goes deep enough, providing a Syntax Cheat Sheet so that one can use it to directly shift the mind from one language to another by going through a single page. It also lists various WebFrameWorks and several Programming Language choices. Am a big fan of Rails and GoLang. The idea is a work in progress..

The wiki is available on github!! It would be nice to collaborate and make it better 🙂

 

C to C++ tour

I was requested during the beginning of this year to give a crash course on C++ for the developers with C background in our company. A while back, sankar gave an introduction to go language using http://tour.golang.org/ . Fascinated by the interface of gotour, I wanted to give the C to C++ tour using a similar interface but needed it in a quick time.

I discussed it with sankar and he came up with https://github.com/psankar/kuvalai/. He masters in pulling people to learning something new 😉 So I quickly learnt a bit of Go and contributed to kuvalai. It was taking a while to get it done, so we discussed and decided to hack up the go-tour. Made it to work with c++!!

Image

Readme.txt – explains howto apply the go tour patches and get it running.

All the programs and the article is now available at https://github.com/chenthillrulz/cpp-tour 🙂 I wanted to put this up on webserver so that it can benefit others, esp. beginners to c++ and students. But since I don’t have any webspace at the moment, thats going to take time 😉

It was really challenging to construct simple, connected, practical examples for demonstrating the features. I wanted this tour to go simply like a movie. I did not know that I would enjoy so much doing this stuff 🙂 Got some happy, encouraging feedback from my peers after the training sessions. Perhaps I should thank my manager, Pradeep for persuading me to do this stuff. And my team, some of whom are still pushing me for the final session!!

Have conducted four sessions and the last one would cover advanced concepts such as traits, functors, template specialization, c++-11 features etc. The last session is taking time as I dont have practical experience on using traits, but still want to get some practical examples 🙂  Working on it!!

The descriptions in the doc. many require some polishing. It has about 42 sections at this point. And as always patches are welcome!!!

writing a blog after quite some time, refreshing 🙂

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]

What is forgiving someone – wonderfully articulated

Forgiveness can never be complete. When you say, “I forgive”, you think the other person is a culprit. However you do it, a little bit still remains. It’s not complete. But when you see the big picture that the culprit is also a victim, a victim of his/her own mind, ignorance or unawareness, compassion arises from within you. – Sri Sri Ravi Shankar

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 🙂