Improvised Tasks.tmbundle for TextMate

Tags


I added commands to the following commands to the Tasks bundle.

  1. Skip a task (toggle)
  2. Expire Skipped tasks

Items marked in cross – ‘X’ change colour to yellow indicate skipped tasks. This is how it looks:

Improvised-Todo-With-Skip-Task

If you want to use it please follow these steps so that you can use it for your presentations/workshops etc…

  1. Git clone: 
    $ git clone git@github.com:DhavalDalal/textmate-bundles.git
    
  2. Change the working dir to:
    $ cd textmate-bundles/
    $ git branch --list
    * master
    

    We need to checkout to the branch – skipped. However, if you notice, its not being shown as a local branch.

  3. So, lets check all the remote branches:
    $ git branch -a
    * master
      remotes/origin/HEAD -> origin/master
      remotes/origin/master
      remotes/origin/skipped
    

    Though the ‘skipped’ branch is there on the remote, we need to track it locally like the master.

  4. Track all remote branches:
    $ git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
    
  5. Verify all our locals for the remotes are created:
    $ git branch --list
    * master
      skipped
    
  6. Update local branches that the track remote branches:
    $ git pull --all
    Fetching origin
    
  7. Switch to Skipped branch:
    $ git checkout skipped
    Switched to branch 'skipped'
    Your branch is up-to-date with 'origin/skipped'.
    
  8. Go to:
    $ cd Review/Bundles
    

    In here, you will find the directory – Tasks.tmbundle

  9. Copy this entire directory to the place where Textmate2 stores its bundles (Usually this is ~/Library/Application\ Support/TextMate/Bundles):
    $ cp -r Tasks.tmbundle/ ~/Library/Application\ Support/TextMate/Bundles/Tasks.tmbundle/
    
  10. Finally, restart TextMate and create a todo list.
  11. Use ⌘K to Skip the task and the same to toggle back to unskip. If no text is selected, the task on the current line is toggled: if it’s pending, it’s marked as skipped and vice versa. If text is selected, every task in the selection is toggled in batch: if any of the tasks are pending, all are marked as skipped; if all are completed, they’re marked as pending.
  12. Press ⌘E to remove skipped tasks in the selection or else the entire document.
Advertisements

Sri Aurobindo’s Integral Education Principles


At the outset, I would not like to distinguish between a mentor, a coach, a trainer and an instructor.  To me this is pedantic.  An educationist is anyone who is educating the other person.   Sri Aurobindo has very beautifully given these 3 principles of Integral education.

  1. Nothing can be taught.
  2. The mind has to be consulted in its growth.
  3. To work from the near to the far.

I use these whenever, I’m coaching – technical coaching or agile coaching, consulting, mentoring or even while playing with kids.    While refactoring, I use the 3rd principle all the times – to work from the near to the far.  What I’ve observed that all these principles are extremely relevant in life (whether you dissect it as personal and professional – it does not matter), not just in education.

During consulting, its extremely helpful to understand the nature and rhythm at which the work and the people (and their temperaments) that i’m involved with and how to go from one level to the next with minimal friction.

For details you can refer to the slides below:

How is Homeopathy is near to Yoga?

Tags


Homeopathy-The-Science-And-Art-Of-Healing

Today I attended the Inaugural function of this book – Homeopathy – The Science and Art of Healing.  Last year Dr. Sharad Shah (I call him Uncle lovingly as the doctor-patient relationship over more than 3 decades has become a personal bond) wrote the book and got it published.  I was happy to receive my personal copy from him.  I started reading it – and what I liked about the book was – he has made the topic of Homeopathy within the grasp of a layman.  I particularly liked the logical build-up of the topics that he has done while weaving it with his personal conflict and history of homeopathy along with detailing the law of similars, and finally the symptoms and prescriptions helpful for anyone.

While reading the Chapter 8 on Concept of Vital Force and in particular Uncle’s bulleted points on elements of Human Life and pointing to Dr. Hahneman’s definition of Vital force wherein he uses the words – spirit, vital force, material body, gifted mind and higher purpose of existence.  When I read these words, I could just connect them to Yoga and told myself – this is how yogic lore looks at the mechanism that we call – human.  I continued reading further without putting any “yoga lens”.   But as I read further, I met sentences like – “uninterrupted flow of vital energy”, “disturbance in vital force causes mal-development”, and the line “disease is a dynamic expression of disturbed vital force” hit me hard.  I could not help but put the “yoga lens”.  I generally read the works of Sri Aurobindo and The Mother.  So, my inquisitiveness led me to Google on what Sri Aurobindo had to say about this?  I found Questions and Answers which Sri Aurobindo had with his personal doctor Dr. Nirodbaran and others in the Ashram.  These were published in the NAMAH journal (Vol 20, Issue 2, 15th July 2012)  by Sri Aurobindo Society. [5]  And in that…to my surprise he says that – “Homeopathy is near to Yoga”.   Now that I had Sri Aurobindo’s words to confirm my finding, I started to read the book again in light of Yoga and what Sri Aurobindo had to say on this.  So in this post, I’ll share with you my findings and present a rational connection between Homeopathy and Yoga – esp. Hathayoga and Mantra Yoga. 

 

Modern Psychology and The Yogic Model

When we look at modern psychology, we find that it puts all thoughts, emotions, impulses, instincts and consciousness into one basket called the “mind”.  However, from psychology of yoga, man’s subjective nature is made up of parts.  Each part has its own awareness or consciousness and thus has its own characteristic attitudes.  At a very broad level, there are 2 divisions in human being – the outer beingconstituting personality of the being (personality derived from the latin word “persona” means mask) and the inner beingthe actual Person using the outer mask.  Ordinarily, we identify ourselves with the outer being and regard it as ourself.[1]  From yogic perspective – this outer being has 3 parts – you can imagine – onion rings – starting with The Physical Body or AnnamayaKosha – अन्नमयकोश, going inwards The Vital Body or PranmayaKosha – प्राणमयकोश and further in – The Mental Body (mind is also a body) or ManomayaKosha – मनोमयकोश.  There are other bodies, but these 3 will suffice our purpose

  • AnnamayaKosha – अन्नमयकोश or food body also called the gross body or स्थूल शरीर.  The food that we eat, gets digested and then assimilated and thus becomes a part of the body…in other words, this physical body is built by accumulation of food and hence the name अन्नमयकोश or the food body. [6]  As I’m a computer engineer, I’ll use the computer as a metaphor –  in that the body is the “hardware” of the human mechanism.   
  • ManomayaKosha – मनोमयकोश or Mental body has to do with facts, thoughts, and knowledge.  Medically, mind and brain are treated the same and consciousness is the outcome of brain activity.  Yogic perspective says that mind and brain are different.  According to Sri Aurobindo the brain is not the seat of thinking.  It is the mind that thinks and the brain is only a communicating channel.   ManomayaKosha is the “software” of the human mechanism.
  • PranmayaKosha – प्राणमयकोश  or Pranic or Vital Body is in between the physical and the mental bodies.  The word vital comes from the latin word – vita or “life”.  Just as there are nerves in the physical body, there is a parallel structure of “Nadis” (नाडी) or nerve-channels or energy pathways exist in the subtle body.  Life-force or Vital force or Prana flows through these Nadis.  We can neither see these Nadis with physical eyes, nor with electron microscope.  These Nadis meet at various junctions and re-distribute again.    So, Pranic body or Vital body is like the electricity that powers the “hardware” and the “software”.  Without this power, neither the physical nor the mental can function or develop further.   It is the means of existence in the material body.

From the psychology of Yoga, each of the Koshas have their own consciousness.

  • Generally,  we look at the body that is something  mechanical.  But the body has its own consciousness and intelligence.  We all know that the heart beats, the liver and kidneys function and the lungs breathe even without our active participation.  In case of illness or injury it will heal itself.  So the body acts from this consciousness and intelligence, all without our mental will or even against it.  The characteristic attitude of physical consciousness is one that of narrowness, rigidity, conservatism, slowness to change, boredom and its habitual modes of action and reaction.
  • Whereas, the vital body is made up of Life-force, desires, emotions, sensations like pleasure, pain etc…, instincts and impulses like anger, fear, lust etc…  The vital consciousness is characterised by attitudes of likes and dislikes, search for pleasure and enjoyment, avoidance of pain and discomfort, desire to possess and accumulate, seeks perpetual variety and change, attachment and repulsion, ambitiousness, aggression, fear and impulsiveness.
  • Whereas Mental is guided by that which is consistent with reason that which is deemed to be true or good.  When mental consciousness is pre-dominant in an individual, the attitude is characterised by rational outlook and it is based on moral and intellectual principles. [1]

In Homeopathy too, when a homeopath takes the case, they study the patient by looking at the physicals, emotional and behavioural traits, mental patterns etc…to arrive at a personality – coincidently these 3 are also the levels which psychology of yoga also concerns itself with.

Mapping-Homeopathic-Miasm-And-Attitudes-of-Consciousness

There are many yogic methods to reach the Ultimate.  Each yoga selects different types of Koshas to reach the highest-level of consciousness.  Hathayoga selects physical body and the vital body as its instruments.  Raja-Yoga selects the mental being as its starting point.

Hathayoga

Hathayoga to me, appears quite nearer to Homeopathy.  Hathayoga uses Physical body as a point of departure to reach the Ultimate, but it does not view it with an eye of a physiologist or an anatomist.  According to Sri Aurobindo – It aims at the conquest of the body and Vital Force (Life-Force  or Prana).   It achieves this using 2 instruments and in 3 steps –

The 2 instruments:

  1. Aasanas – They develop in the body certain attitudes of immobility.  If the body is restless, it cannot hold the Pranic energy that enters or is generated within the system.  So aasanas deal with more material part of the physical totality, but it needs assistance of Pranayamas.
    • First aim is to get the body rid of its restlessness (establish control by physical immobility) and
    • Second aim is to force the body to hold the Pranic energy instead of squandering or dissipating it (develops power by immobility).
  2. Pranayamas – Deals directly with the subtler vital parts – the nervous system.  प्राणायम = प्राण (Life-force or Vital energy) + यम (yama means control).  It refers to the control of Life-force.  Pranayamas do the regulated direction and arrestation of vital force in the body.  It achieves this by control of breath – that includes inhalation/exhalation and varieties of rhythmic patterns, inholding and outholding the breath, bandhas or locks.  When the breath is held, the energy within is also held, this holding of energy causes pressure build up and with the release of breath, the blocked energy is unleashed and during the release process, it removes the energy blockages.
    • First aim of Pranayama is to purify the nervous system, to circulate life-force through all nadis without obstruction, disorder or irregularity and
    • Second to acquire complete control of its functionings.   This is done so that mind and soul do not become subject to body or vital or their combined limitations.

In 3 steps:

  1. Purification – Removal of aberrations, obstructions, disorders brought about by mixed and irregular action of the energy in our physical, moral and mental system.
  2. Concentration – Bringing to its full intensity, the mastered and self-directed use of vital energy.
  3. Liberation – Release our being from the painful knots of individualised energy in a limited play, so that union with the Divine is achieved.[3]

How is Homeopathy near to Yoga?

If we observe carefully, in Homeopathy the medicinal remedy removes obstructions and re-establishes vital energy balance in the system.  Whereas in Hathayoga, Asanas and Pranayamas remove interruptions, obstructions, disorders and re-balance vital energy in the system.   In Homeopathy, the effectuation is on the vital body and then changes are seen in the physical body.  In Hathayoga, effectuations are on the physical and the vital body.  Homeopath gathers insights from individual’s personality as a window to peep within and then select the remedy based on law of similars.  In Hathayoga, there is no such need to gather such insights.  It  is beneficial to whoever practices.  Homeopathy and Hathayoga complement each other and can be used simultaneously.

Mantra Yoga

Now let’s turn the attention to Mantra and Mantra Yoga.  In the word Mantra (मंत्र), the root sound is Man (मन) मन means to think, to understand, to contemplate, to perceive, to comprehend and the suffix – त्र (Tra) is used in the sense of instrumentality, meaning as Instrument.  Therefore, the word mantra means Instrument for contemplation, meditation, perception, comprehension, thinking etc…  Just as asanas serve as an instrument to bring the power of immobility in the material body, mantra is an instrument that arrests the restlessness of the mind and makes it still.  So, it is just the parallel of Aasanas, but for mind.  When mind is noisy, disturbed, opinionated, critical, reactive, or simply addicted to sensory sources of stimulation and entertainment, it squanders and dissipates lot of vital energy generating lot of negative thought and emotional patterns of fear, perverted desires, hatred etc…in the mental field.  All of these ultimately affect the circulation of Prana.  Just like aasanas, Mantra practice gradually calms the mind and eventually stills the mind.  Once the composure is achieved, the mind becomes silent, concentrated and reflective.  This naturally leads to meditation, and gives us focus and energy to go beyond the mind.[4]  This is Mantra Yoga.  All yogic methods – Hathayoga, Jnana Yoga, Bhakti Yoga etc… employ Mantras to prepare the mind for deeper practices.

My Personal Observations

  • So, one of the things that I found strikingly similar between Homeopathy, Hathayoga and Mantrayoga is that all address the vital force to remove obstruction and ensure freely circulating Prana.
  • Another thing that I observed is that what we call resonance in physics, the Mantras are also based on resonance to remove vital-force disturbances, the अंगस्पर्श (Angasparsha – touching different parts of body – See section Aspirated in this post) of Tantra yoga and  Homeopathy is based on Law of Similars to remove vital-energy disturbances caused by the disease-energy, to me this is also a form of resonance…so I’m wondering whether the inner movement behind external forms of resonance are similar?  That is a topic of my personal interest and research…

References

  1. Looking from Within –  A seeker’s Guide to Attitudes for Mastery and Inner Growth. Ed. A. S. Dalal
  2. Homeopathy – The Science and Art of Healing – Dr. Sharad Shah.
  3. The Synthesis of Yoga – Chapter XXVII – Hathayoga pp 506-513, Sri Aurobindo
  4. Mantra Yoga and Primal Sounds – Dr. David Frawley (Pt. Vamadeva Shastri)
  5. NAMAH Journal, Vol. 20, Issue 2, 15th July 2012.  Sri Aurobindo Society.
  6. Three Truths of Well-Being – Sadhguru

Agile India 2018 Conference


Announcing the 14th edition of Agile India Conference with brand new themes and a fabulous lineup of speakers. Agile India is Asia’s Largest & Premier International conference on Leading Edge Software Development Methods.

Meet:

  • Alan Cooper – The Father of Visual Basic, Creator of Goal-directed Design methodology and inventor of the Persona concept
  • Steve Denning – Author of several books on Management, Leadership, Innovation and Organizational Storytelling
  • Linda Rising – Author of four books, most recently the Fearless Change
  • Gregor Hohpe – Author of Enterprise Integration Patterns. Technical Director at Google Cloud Computing
  • James Stewart – Co-founder of the Government Digital Service and x-Deputy CTO of the UK Government
  • Bjarte Bogsnes – Author of Implementing Beyond Budgeting, Chairman of Beyond Budgeting Roundtable and Senior Advisor Performance Framework at Statoil
  • Dr. Denis Bauer – Team Leader and Research Scientist in Cloud Computing in Transformational Bioinformatics at CSIRO
  • Jeff Patton – Author of User Story Mapping and the person responsible for bringing user-centered design thinking to Agile world
  • And 70 more thought leaders from 14 countries

The program spreads across 8 days (March 5-11th 2018, Bengaluru) with two pre-conference plus two post-conference workshop days and four days of conferences in between:

  • March 4-5th: Pre-Conference Workshops from our international experts
  • March 6th: Business Agility Day – Hosted by Agile Alliance
  • March 7th: Design Innovation Day – Hosted by Cooper
  • March 8th: Digital Transformation Day
  • March 9th: DevOps and Continuous Delivery Day – Hosted by Red Hat
  • March 10-11th: Post-Conference Workshops from our international experts

Schedule: Check out conference schedule for the lineup of workshops and speakers.

Tickets: Conference registration is now open and Smart Price offers are going away soon. Register now for best deals!!

Check out the exciting offers for bulk registrationshttps://2018.agileindia.org/agile-india-2018-bulk-booking-offers/.

Sponsors: We thank Scrum.org, AddTeq/Atlassian, Scaled Agile, ICAgile and Scrum Alliance for sponsoring the conference.

If your organization wants to support this non-profit, volunteer-run conference, please check out sponsorship options.

Look forward to meeting you at the conference!!

Paradigms CodeJugalbandi


This year at Functional Conf 2017, Morten Kromberg, CXO of Dyalog Ltd. and myself presented CodeJugalbandi again. The theme was about exploring paradigms. We looked at Object-Oriented, Functional Programming and Array-Oriented Paradigms solving the same problem statement. Given the 45 mins time-frame, we were able to Jugalbandi first 2 melodies. Conversations between two artists can be viewed by clicking the links below, or you can simple watch the embedded Youtube video herein.

Melody Name Paradigms Explored Languages Used
Control Flow and Data-Driven Imperative, Functional Programming and Array-Oriented Paradigms Haskell and APL
Abstractions and Transparency Object-Oriented, Functional Programming and Array-Oriented Paradigms JavaScript and APL
Macro and Micro Functional Programming and Array-Oriented Paradigms Scala and APL

 

 

Slides are simply an index to the melodies.

Functional Conf 2017 – Last Chance to Register – Bangalore – Nov 16-19


Functional Conf is a premier conference on Functional Programming. Since its origin, back in 2014, this event has been a melting-pot for functional programmers from around the world. Currently, functional programming is at the heart of every new generation programming technology and diverse companies are employing functional programming to actuate more effective, robust, and flexible software development. This has given birth to an extremely vibrant community of functional programmers. We are thrilled to partner with GreyOrange, Go-Jek, Erlang Solutions and Dyalog, who share our vision and enthusiasm to foster a community of functional programmers.

This 4th edition of Functional Conf will see participation from 137+ Companies from 13 countries. The conference program contains 45 sessions from 37 speakers covering functional programming in 17 languages – apl, csharp, elixir, elm, erlang, eta, fsharp, haskell, idris, java, javascript, ocaml, php, purescript, rust, scala and swift.

Register at https://confengine.com/functional-conf-2017/register

Agenda:

  • Nov 16th – Pre-Conference workshops
  • Nov 17th – Erlang and Elixir Factory Lite India (First time in India)
  • Nov 18th – Functional Conf
  • Nov 19th – Post-Conference workshops

Pre/Post Conference Workshops:

Nov 16th:

Nov 19th:

Full conference schedule: https://confengine.com/functional-conf-2017/schedule

Dots and Boxes Game in Erlang


I remember playing this pencil and paper game as a kid and it served as a good past-time.

The rules for this game are very simple. The game is very well described here, but I have jotted them here for inline view

  • game begins with empty grid of dots
  • players take turns at adding a horizontal or vertical line between two un-joined adjacent dots
  • a player who completes the fourth side of a 1×1 box earns a point, writes their initials in the box and gets another turn.
  • game is over when there are no more lines that can be placed
  • winner is the player with most boxes
  • the board can be of any size 2×2, 5×5 works well for experts

I’ve coded this game in Erlang, both Sequential and Concurrent. Below is the game output resulting from auto play.

1> dots_and_boxes:auto_play(["foo", "bar"],3,3).
+   +   +

+   +   +

+   +   +

"foo" playing...
+   +   +

+   +   +

+   +---+

"bar" playing...
+   +   +
        |
+   +   +

+   +---+

"foo" playing...
+   +   +
|       |
+   +   +

+   +---+

"bar" playing...
+   +   +
|       |
+---+   +

+   +---+

...
...
...

"bar" playing...
+---+---+
|foo|foo|
+---+---+
|bar|bar|
+---+---+

*** Game Over ***
Game has Drawn!!
Detailed Results: [{"foo",2},{"bar",2}]

Implementation in Sequential Erlang

The entire module is broken down into following groups of functions:

  1. Core functions related to actual playing of the game: Set-up the game and players. Play one player at a time, manually. Functions used for manual play are: dots/2, boxes/1, join/4. In case you want to render the game on screen, use draw/1.
    -module (dots_and_boxes).
    -export ([dots/2, boxes/1, join/4, draw/1, auto_play/3]).
    
    -type point() :: {integer(),integer()}.
    -type line() :: {atom(), point(), point(), boolean()}.
    -type dots() :: [point()].
    -type box() :: {atom(), [line()], string()}.
    -type grid() :: [box()].
    
    -spec dots(integer(), integer()) -> dots().
    dots(XDots, YDots) ->
      [{X,Y} || X <- lists:seq(0, XDots - 1), Y <- lists:seq(0, YDots - 1)].
    
    -spec boxes(dots()) -> [box()].
    boxes([]) -> [];
    boxes(Ds) -> boxes(Ds, 1, length(Ds), []).
      
    boxes(Dots, Begin, End, Bs) when Begin =< End ->
      Dot = lists:nth(Begin, Dots),
      BoxPts = box_points_for(Dot),
      case all_present(BoxPts, Dots) of
        true -> 
          B = {box, lines(BoxPts), []},
          boxes(Dots, Begin + 1, End, [B | Bs]);
        false -> 
          boxes(Dots, Begin + 1, End, Bs)
      end;
      
    boxes(_,_,_,Bs) -> lists:sort(Bs).
      
    all_present(BoxPts, Pts) -> BoxPts -- Pts == [].
      
    box_points_for(BottomLeft) ->
      {X1, Y1} = BottomLeft,
      BoxSize = 1,
      X2 = X1 + BoxSize, Y2 = Y1 + 1,
      BottomRight = {X2, Y1},
      TopRight = {X2,Y2},
      TopLeft = {X1,Y2},
      [BottomLeft,TopLeft,TopRight,BottomRight].
    
    lines([BottomLeft,TopLeft,TopRight,BottomRight]) ->
      %clockwise lines in a box
      [{line,BottomLeft,TopLeft,false}, 
       {line,TopLeft,TopRight,false}, 
       {line,TopRight,BottomRight,false}, 
       {line,BottomRight,BottomLeft,false}].  
      
    -spec join(point(),point(),string(),grid()) -> {grid(), boolean()}.
    % return pair contains a boolean to indicate
    % take another turn for the last player.
    join(D1, D2, Player, Grid) ->
      NextG = [mark_box(B,D1,D2,Player) || B <- Grid],
      {NextG, was_box_signed(Grid, NextG)}.
    
    was_box_signed(PrevG, NextG) ->
      PPs = [B || B <- PrevG, signed_box(B)],
      NPs = [B || B <- NextG, signed_box(B)],
      length(NPs) - length(PPs) == 1. 
    
    signed_box({box,_,P}) -> P /= [].
    
    % 4 arg mark_box
    mark_box(B = {box,Lines,[]}, D1, D2, Player) ->
      PlayerLine = {line,D1,D2,false},
      case contains(PlayerLine, Lines) of
        true -> signBox(mark_box(D1,D2,B), Player);
        false -> B
      end;
      
    mark_box(Box,_,_,_) -> Box.
    
    signBox(MBox = {box,MLines,_}, Player) ->
      case fourth_side_complete(MBox) of
        true -> {box,MLines,Player};
        false -> MBox  
      end.
    
    % 3 arg mark_box
    mark_box(D1, D2, {box,Lines,[]}) ->
      MLines = lists:map(fun 
        ({line,A,B,false}) when ((A==D1) and (B==D2)) -> join_dots(D1, D2);
        ({line,A,B,false}) when ((A==D2) and (B==D1)) -> join_dots(D2, D1); 
        (Line) -> Line
      end, Lines),
      {box,MLines,[]}.
    
    contains(_, []) -> false;
    
    contains(Line = {line,A,B,false}, [L|Ls]) ->
      case L of 
        Line -> true;
        {line,P,Q,false} when (A==Q) and (B==P) -> true;
        _ -> contains(Line, Ls)
      end.
      
    fourth_side_complete({box,Lines,_}) ->
      lists:all(fun({line,_,_,Marked}) -> Marked == true end, Lines).
      
    join_dots({X,Y1}, {X,Y2}) when abs(Y2-Y1) == 1 -> 
      {line,{X,Y1},{X,Y2},true};
    join_dots({X1,Y}, {X2,Y}) when abs(X2-X1) == 1 -> 
      {line,{X1,Y},{X2,Y},true};
    join_dots(_, _) ->
      badarg.
    
  2. Auto-play functions: Set-up the grid and players, call auto_play/3 and watch the game run to completion. auto_play/3 uses draw/1 function.
  3. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
    % All Auto Play related functions
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
    
    -spec auto_play([atom()], integer(), integer()) -> [any()].
    auto_play(Players, XDots, YDots) when (XDots >= 2) and (YDots >= 2) and (length(Players) >= 2) ->
      Grid = boxes(dots(XDots, YDots)),
      % io:format("Initial Grid = ~p~n", [Grid]),
      draw(Grid),
      play(Players, Grid, fun() -> rand_dots_pair(XDots, YDots) end);
    
    auto_play(_, _, _) ->
      io:format("Choose more than 2 players and have number of dots in X and Y direction as atleast 2!~n").
        
    play(Players, Grid, RandF) ->
      case game_over(Grid) of
        true -> show_results(Grid);
        false -> continue_play(Players, Grid, RandF)
      end.
      
    continue_play(Players = [P|Ps], G, RandF) -> 
      io:format("~p playing...~n", [P]),
      {NextG, SamePlayerTurn} = turn(P, G, RandF),
      draw(NextG), 
      case SamePlayerTurn of 
        true -> 
          io:format("~p taking another turn!~n", [P]),
          play(Players, NextG, RandF);
        false -> 
          play(lists:append(Ps,[P]), NextG, RandF)
      end.
    
    show_results(Grid) ->
      All = [{Winner, Score}|Losers] = results(Grid),
      io:format("*** Game Over ***~n"),
      case lists:keymember(Score, 2, Losers) of
        true -> io:format("Game has Drawn!!~n");
        false -> io:format("Winner => ~p~n", [Winner])
      end,
      io:format("Detailed Results: ~p~n", [All]).
    
    results(Grid) ->
      Ps = [P || {box,_,P} <- Grid],
      Rs = frequency(Ps),
      lists:reverse(lists:keysort(2, Rs)).
        
    game_over(Grid) -> 
      lists:all(fun signed_box/1, Grid).
      
    frequency(Xs) -> frequency(Xs, []).
    frequency([], Acc) -> Acc;
    frequency(Xs = [X|_], Acc) -> 
      {Ys,Ns} = lists:partition(fun(E) -> E == X end, Xs),
      frequency(Ns, [{hd(Ys),length(Ys)} | Acc]).
      
    turn(Player, Grid, RandomF) ->
      {D1,D2} = RandomF(),
      case line_not_exists(D1, D2, Grid) of
        true -> join(D1, D2, Player, Grid);
        false -> turn(Player, Grid, RandomF)
      end.
    
    line_not_exists(D1, D2, Grid) ->
      Line = {line,D1,D2,false},
      GLines = lists:foldr(fun({box, Lines, _}, A) -> lists:append(A, Lines) end, [], Grid),
      contains(Line, GLines).
      
    rand_dots_pair(XDots, YDots) ->
      D1 = rand_dot(XDots,YDots),
      D2 = rand_dot(XDots,YDots),
      case distance(D1, D2) == 1 of
        true -> {D1,D2};
        false -> rand_dots_pair(XDots, YDots)
      end.
    
    distance({X1,Y1}, {X2,Y2}) -> 
      math:sqrt((X2-X1)*(X2-X1)+(Y2-Y1)*(Y2-Y1)).
      
    rand_dot(XDots,YDots) -> {rand(XDots),rand(YDots)}.
      
    rand(N) when N >= 2 -> rand:uniform(N) - 1.
    
  4. ASCII drawing related functions: This is the main function draw/1 which consumes the grid to be drawn. The way it does this is by creating raster lines from grid data and renders it on screen as ASCII art. Game lines are partitioned as horizontal lines and vertical lines. For example – In a box, a horizontal line is one that joins two dots horizontally and a vertical line is on that joins two dots vertically. Rasterize renders the game with alternating horizontal and vertical lines. In the process, it also renders player initials (first 3-letters) inside a box, if that box belongs to the player.
  5. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % All drawing related functions
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    rasterize(Grid) ->
      GridLines = lists:flatmap(fun(B) ->
         annotate_lines(B) 
      end, Grid),
      Lines = lists:filter(fun({_,Aligned,_}) ->
        Aligned /= vertical_left_ignore
      end, GridLines),
      {HLines,VLines} = lists:partition(fun({_, Aligned, _}) -> Aligned == horizontal end, Lines),
      SortedHLines = lists:usort(HLines),
      {{_,_,{X,Y},_},_,_} = lists:last(SortedHLines),
      rasterize([], 0, 0, X, Y, SortedHLines, VLines).
    
    rasterize(Acc, _, _, _, _, [], []) -> Acc;
    
    rasterize(Acc, _, _, _, _, HLines, []) -> 
      lists:append(Acc, [[HLines,[]]]);
    
    rasterize(Acc, X, Y, XMax, YMax, HLines, VLines) when (X =&lt; XMax) or (Y =
      {Hs,HLs} = lists:partition(
        fun({{_,{_,Y1},{_,Y2},_},_,_}) -> 
          (Y1 == Y) and (Y2 == Y) 
        end, HLines),
      {Vs, VLs} = lists:partition(
        fun({{_,{_,Y1},{_,Y2},_},_,_}) -> 
          (Y == Y1) and (Y2 == (Y + 1)) 
        end, VLines),
      NewAcc = lists:append(Acc,[[Hs,lists:sort(Vs)]]),
      rasterize(NewAcc,X+1,Y+1,XMax,YMax,HLs,VLs).
      
    -spec annotate_lines(box()) -> [any()].
    annotate_lines(B) ->
      {box,[VLeft,HUpper,VRight,HLower],TakenBy} = B,
      [
        {sort_line(HLower),horizontal, []},
        {sort_line(VRight),vertical_right, TakenBy},
        {sort_line(HUpper),horizontal, []},
        case VLeft of
          {line, {0, _}, {0, _}, _} -> 
            {sort_line(VLeft),vertical_first_col, []};
          _ ->
            {sort_line(VLeft),vertical_left_ignore, []}
        end
      ].
      
    sort_line({line, D1, D2, Present}) when D1 > D2 ->
      {line, D2, D1, Present};
    sort_line(L) -> L.
        
    draw(Grid) ->
      % io:format("Grid = ~p~n", [Grid]),
      RasterLines = rasterize(Grid),
      % io:format("RasterLines = ~p~n", [RasterLines]),
      lists:foreach(fun([RLines, CLines]) ->
        draw_row_lines(RLines),
        draw_col_lines(CLines)
      end, RasterLines).
    
    draw_row_lines(Lines) ->
      lists:foreach(fun(Line) -> 
        case align(Line) of
          horizontal -> io:format("+---");
          horizontal_blank -> io:format("+   ")
        end 
      end, Lines),
      io:format("+~n").
                     
    draw_col_lines(Lines) ->
      lists:foreach(fun(Line) -> 
        case align(Line) of
          {vertical_blank, first_column} ->     
            io:format(" ");
          {vertical, first_column} -> 
            io:format("|");
          vertical_blank -> 
            io:format("    ");
          vertical -> 
            io:format("   |");
          {vertical, TakenBy} -> 
            io:format("~3s|", [TakenBy])
        end
      end, Lines),
      io:format("~n").
      
    align({Line, vertical_first_col, _}) ->
      case Line of
        {line,_,_,false} ->
          {vertical_blank, first_column};
        {line,_,_,true} ->
          {vertical, first_column}
      end;
    
    align(LInfo = {_, vertical_right, TakenBy}) ->
      case LInfo of 
        {{line,_,_,false},_,_} -> vertical_blank;
        {{line,_,_,true},_,[]} -> vertical;
        {{line,_,_,true},_,TakenBy} -> {vertical, TakenBy}
      end;
    
    align({Line, horizontal, _}) -> 
      case Line of
        {line,_,_,false} -> horizontal_blank;
        {line,_,_,true} -> horizontal
      end.
    
  6. Generic functions: zip two lists using a function, transpose a matrix and find index of an item
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generic functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

zipwith(F, Xs, Ys) ->
  zipwith(F, [], Xs, Ys).

zipwith(_F, Acc, [], []) -> Acc;  
zipwith(_F, Acc, _Xs, []) -> Acc;  
zipwith(_F, Acc, [], _Ys) -> Acc;    
zipwith(F, Acc, [X|Xs], [Y|Ys]) ->
  zipwith(F, lists:append(Acc, [F(X,Y)]), Xs, Ys).

transpose([[]|_]) -> [];
transpose(M) ->
  [lists:map(fun hd/1, M) | transpose(lists:map(fun tl/1, M))].
    
index_of(Item, List) -> 
  index_of(Item, List, 1).

index_of(_, [], _) -> not_found;
index_of(Item, [Item|_], Index) -> Index;
index_of(Item, [_|Tl], Index) -> index_of(Item, Tl, Index + 1).

All the Erlang code is available in this repository https://github.com/DhavalDalal/Dots-And-Boxes-Erlang

Implementation in Concurrent Erlang

The activities of playing a game and rendering are completely different and can happen in different processes. To that end, there are two server processes, one for playing the game, a.k.a. game_server and another for rendering the game as a text ui, a.k.a render_server.

These are both supervised using a game_supervisor. Game client(s) talk to the supervisor. The supervisor routes the request either to the game server or the render server appropriately.

             
                      +-------------------------------+
                      |                               |
                      |                          +----------+ 
                      V                         /|  Render  |
+--------+      +----------+                   / |  Server  |
|  Game  |----->|   Dots   |      +----------+/  +----------+
| Client |      |   And    |----->|   Game   |
|  1..n  |<-----|  Boxes   |      |Supervisor|    
+--------+      +----------+      +----------+\  +----------+
                 Game ^             Router     \ |   Game   |   
                      |                         \|  Server  |  
                      |                          +----------+ 
                      |                               |
                      +-------------------------------+

In case any of the servers die, they are restarted by the supervisor. If a game_server dies all the clients associated with it die too (as the game server maintains games for all the clients and is thus carries state). However, if a render_server dies, no clients are affected and is also restarted by the supervisor.

Note: I’ve done Custom Server implementation, and next is Gen Server implementation that I plan to do next.

धातुरहस्य (Dhāturahasya) – Unfolding the secret of root sounds in Sanskrit – An Introduction.


I plan to post day-by-day learnings out of this workshop. So these are just notes that I’ve scribed during the sessions for my future reference. As a side-effect, you may benefit from it. However, as I’m learning Sanskrit, there may be many mistakes or loss during translation, so be cautious. In other words, mistakes are entirely mine! At some places, there are things that I’ve added and I’ll state it explicitly.

At the outset, I would also like to thank Dr. Sampadananda Mishra for taking the time out and offering to correct the posts whenever his schedule permits him. Accordingly, I’ll make corrections and improve it. He is yet to correct this post (once he reviews it, I’ll remove this line).

Like the earlier workshops after the introductions, he told us how he conceived the idea of this workshop and how and why he arrived at the name धातुरहस्य (Dhāturahasya) for this workshop.

Sampadanandji made it clear that he is not going to deal with the deeper technicalities of धातु (Dhātu) from the grammatical tradition of Panini, although this will be discussed. Though the workshop has technical sessions, but much of the focus will be on the deeper philosophical aspects. What he mainly intends to give the participants is the philosophy behind the root sounds and he said this is what he has learnt from Sri Aurobindo’s writings. After reading Sri Aurobindo’s essays on the Gita, Upanishads and the Vedas, he said that he found a tremendous depth and once having been at that depth, one does not want to return back to refer/hear any other commentaries.

Sri Aurobindo has given a clear insight that until we go to the very root of the experience behind every thing, it is extremely difficult to understand the spirit behind those experiences that are manifested in the form of mantras or the experiences that are brought forth in the Vedas in the form of language.

Sampadanandji pointed out further that in every aspect of our day-to-day life here at the Sri Aurobindo Society, we begin with Silence. He says that this Silence is the ultimate source of the all the speech world! So how do we enter in to that world? This further lead to an enquiry by Sampadanandji that how Sri Aurobindo was able to learn Sanskrit in just few months and how our ancient yogis understood almost all languages? They even understood the language of the inanimate objects! How The Mother understood the language of the flowers? She has given spiritual significance of almost 900 flowers! When she was questioned how was she able to do that? She replied saying that in deeper contemplation she would enter in to the very Consciousness of the flowers and listen to their languages. In this way she has created a new language of sadhana by going deep into the very consciousness of the flowers. So it is from this perspective that the study of the language needs to be approached.

Also, it is not the mastery of the language which will help us go beyond and understand things. Many well-versed professors of English cannot understand what Sri Aurobindo has written. As people suggest, Sri Aurobindo’s English is considered to be top-grade, of extra-ordinary quality! In fact, this has been the experience of many people. On the other hand, there are people who have had no formal education, and they probably know very little English. But, they enjoy reading Sri Aurobindo and they explain it to others in a very simple and lucid manner. He also gave the example of Vashistha Ganapati Muni (a disciple of Sri Ramana Maharishi). He never took up study of English (as he was स्वदेशी [Swadeshi] kind of person), refused to look at English characters (on hoardings etc…), never signed in English – that level of strictness. However, he used to translate into Sanskrit the whole idea of The Secret of the Vedas of Sri Aurobindo. He translated entire Sri Aurobindo’s book – The Mother. When it was read out to Sri Aurobindo, he said that he must meet the Poet. He has brought out the spirit of the text. When someone asked Sri Aurobindo that even though the Muni did not know English, how could he possibly grasp, express and translate the whole essence of the book? Sri Aurobindo said – It is not the language which is the barrier, those who open themselves to the Truth they clearly see the Truth behind the symbols and the characters of the language. This was the secret even with Sri Aurobindo of how he mastered the whole language. So, in order to understand the language and take up the study of the language we must keep this in the background as a reminder.

Sampadanandji then laid down the order of topics for the workshop:
1. The Origin of the Language – An Indian Perspective
2. The System of Seed Sounds – Part 1
3. Sanskrit – A Mantric Language. Ultimately, धातुरहस्य (Dhāturahasya) is rooted in the whole concept of Mantra.
4. Deeper spiritual significances of Seed Sounds – बिजाक्षर (Bijakshara) and बिजमन्त्र (Bijamantra) – 2 sessions
5. Mechanism of word derivation from the root sounds.
6. Activity sessions on discovering the root sounds.
7. How to understand scriptures with the help of root sounds (not just a mental understanding) but by getting in to its spirit. It is extremely difficult to get into the spirit of the scriptures without delving deeper into the roots and the fundamental experiences associated with each of those sounds. If one does not do that, then it can lead to interpreting the scriptures quite differently, and eventually fail to bring out the coherence between what is said and what is meant (not the surface meaning, but stemming from the experiences behind the sounds). This is the main reason why we find multitude of interpretations for a given scripture. Something very unique to Sri Aurobindo is – he has presented the whole concept of root sounds, comparative philology in this light in the book Complete Works (new volume) – Vedic and Linguistic Studies recently published by Sri Aurobindo Ashram.

So, how do we understand the secret of languages and in-turn understand ourselves and the world? But, why ourselves? This is because the entire aim of education in the ancient times and all the principles of education that Sri Aurobindo has laid down is all rooted in the vision of the Rishis that the sole aim of education is आत्मानं विद्धि (AAtmanam Viddhi) – Know thyself.

If you study Panini’s text which is extremely technical or Vātsyāyana’s Kamasutra , or any text on Vaastu Shastra or any books on Physics, Chemistry, you will find that they have never deviated from this whole aim of आत्मानं विद्धि (AAtmanam Viddhi) – Know thyself. In Panini’s text, the philosophy of creation, the philosophy of Self and the language, the technique, the Grammar, the very way of presentation always are hand-in-hand and completely in harmony with each other.

Before we approach study of any language, we need to understand that every language has its own स्वभाव (Svabhava – Extrinsic Nature), स्वधर्म (Svadharma – Unique Intrinsic Nature) and its own spirit. Just as every language has its own स्वभाव and स्वधर्म and spirit, so does Sanskrit. In the schools and institutes, where the language is taught formally, the first thing they do is teach the structure of the language – its grammar, parts of speech etc…, but they fail to dive deeper without giving any sense on the स्वभाव and स्वधर्म of the language itself.

My personal note: This is one of the reasons why I come to Sri Aurobindo SocietySAFIC to learn Sanskrit. There are many commercial/non-commercial places where one can embark on their Sanskrit learning journey, but what I learn here is like drinking directly from the fountain.

Sampadanandji further emphasized that – at present, whatever the ancient Rishis have communicated using their language is difficult to understand if we simply follow the mental understanding of it, i.e., by accepting the language in a very formal way (without diving deep into its स्वभाव and स्वधर्म). It will then look very different, and thus will leave a huge gap. However, if one enters in to the spirit of the language, by understanding the स्वभाव and स्वधर्म, then one can observe that there is a continuum in the language since its beginning. This has been maintained by Sanskrit through the times despite Vedic Sanskrit being different from Classical Sanskrit.

Sampadananji categorically told the participants that for this workshop do not stress on learning the language, even if you learn few sentences or one mantra, or few words, its okay because it is important to carry the right attitude and feel the force behind the language. Feeling the language will make the learning easier than doing it formally. Patanjali says –

एकः शब्दः सम्यग्ज्ञातः सुप्रयुक्तः स्वर्गे लोके च काम धुग भवति

Contextualizing it this to the workshop, it roughly translates as – Though you may know one word, know it well, use it in the right sense, at the right place and with the right attitude. If one feels this consciousness, the experiences and the force behind the sound, then you have achieved much more than the scholar who is fluent in Sanskrit, who can explain the shlokas, but is devoid of the feel for the spirit of the language.

Sanskrit has been designed for self-realisation, in fact, it’s the language of self-realisation. Studying Sanskrit in its right way is to take up the Sadhana of self-realisation, it is आत्मानं विद्धि the vision of seers and sages.

Now, let us look at the features of Sanskrit:
1. Each word is self-explanatory.
2. It is a property-based language.
3. It is an inflectional language.

Let us dwell on each.

1. Each word is self-explanatory: The first thing that anyone learns in a language are words. Have you ever wondered why a particular word is used in a particular sense? Most of the times we take it for granted, we don’t even ask this question. Lets look at English and take up the word – Hand. If we ask someone, do you know the meaning of the word Hand? Chances are you will be ridiculed. Its called Hand because it’s a Hand. Don’t you know that? So, basically you are not allowed to ask this question – Why a hand is called hand? You may find an answer when you look at the history of the language. Words in English are by and large imported from other languages or they have evolved out of convention that became sufficiently strong in use. For words that have evolved out of convention lack the inherent significance, that is, they are not self-explanatory. However, this is not true with Sanskrit and languages derived directly from Sanskrit. In Sanskrit, each and every word is self-explanatory. Sometimes, you don’t have to refer to dictionary! If you have a good introduction to the Dhātus (धातु), to the root sounds and the senses behind them, you don’t need to refer to dictionary every-time. The word itself will explain you why it stands for a particular object or an idea. This is the first important feature of the language.

2. It is a property-based language: Please refer to earlier workshop notes here. Sampadanandji reminded us that when using words in this language that they are property based, they deal with property and this must be consciously held in mind all the time. For example, he asked a wonderful question – What does the word ऐक (Eka) mean? ऐक (Eka) does not mean one as a mathematical value, but it means the property of being one. In which form ऐक (Eka) can be used? Is it singular, dual or plural? ऐक (Eka) means singular, but in Sanskrit we find plural form of ऐक (Eka) called ऐके (Eke).

For example, the usage of singular form would be – ऐक: बालक: पठति (A boy is reading).

We can also form sentence with plural form as – ऐके बालका: पठन्ति (A group of boys are reading).

One can grasp this only when one looks it as a property. They have maintained the property of being one – as a group, as a unit or unity or harmonious aspiration as a group. So it means there is one group of boys doing certain action (in our case reading). When you pick up any entity from the same group, they represent the same thing, this is ऐके. This how we explain that though there are many boys, the property of being one is not lost. In a general sense, one can use ऐके where you have many maintaining the property of being a single unit.

Similarly one can have singular form of सर्व (Sarva means all) and the plural form as सर्वे (Sarve) – it is the property of being all but taking care of the multiplicity. When one deals with this as property then only this can be explained. To understand we need to look at the property it describes and not the object. To enter into the property one has to go deep, decode, analyse and get into the root sound. Getting into the root sound is the first step and then there are subsequent steps to get into the spirit of the root sounds. A mere knowledge of root sound will not help to get into the deeper aspect of the language.

3. It is an inflectional language.: There are many inflectional languages all over the world, Sanskrit is one of them. Comparatively Sanskrit probably has the highest degree of inflection. Due to this high degree of inflection, Sanskrit instills a deep sense of freedom of expression to its users. One is free to use existing words (as experienced by other people), however, one is not bound to use them. Users can also create their own words (based on the their experience with the object). Further, the user is free to use the language in a way one wants, that is, one is not bound to follow the subject-predicate structure. The user can put the subject anywhere they want, they can put the object anywhere they desire. There is no formal word order in Sanskrit. However don’t take it as a वेद वाक्य (Gospel in English), there are a few situations where the word order in a sentence needs to be respected. So, Sampadanandji calls Sanskrit as a language of freedom and consciousness. Now 99% of the Sanskrit is available as a poetry…science, mathematics, literature etc…poetry is the very soul of this language. In poetry there is no word order, so you need an अन्वय (anvaya). Wikipedia says

Anvaya refers to the logical connection of words, as to how different words relate with each other to convey a significant meaning or idea.

Main aim of अन्वय is to arrange the words following the sequence of ideas flowing as thoughts. Its purpose is to decode, enter into the mind of the poet and grasp the spirit behind the thought. अन्वय (Anvaya) = अनु (Anu) + वय (Vaya). Anu means to follow and Vaya means to weave.

If you observe closely, अन्वय prepares your mind for the realisation of what is behind a particular verse. This is the secret of the mantras, sounds, and verses in Sanskrit. It prepares the mind for realisation by following the train of thoughts like this and realise the spirit of what is being said. However, it is not to be misused for converting poetry to prose.

If you are a beginner in Sanskrit (like me) and you just have words to express your idea, then you simply arrange them the way in which you think without worrying about the order. You simply put the words anywhere you want. For example, you want to say the boy goes to the school in the morning. You can translate this sentence like this – बालक: (The boy) गच्छति (goes) विद्दयालयम (to the school) प्रात:काले (in the morning).

Now in other languages you will not be allowed to put words in any order. However, in Sanskrit you can put words as it appears in your train of thoughts. So if you happen to go from right to left instead, you can say – प्रात:काले (in the morning) विद्दयालयम (to the school) गच्छति (goes) बालक: (The boy) and it is perfectly valid.

If you happen to spot words randomly to gather the meaning of the sentence you can also say – गच्छति (goes) विद्दयालयम (to the school) बालक: (The boy) प्रात:काले (in the morning). Again this is perfectly valid Sanskrit.

You simply put down the words in any order and express your idea. This to me is a big wow, because we spend so much time re-arranging our words to form a meaningful sentence to convey our idea. So, this flexibility and freedom that Sanskrit allows works with the grain of thought and not against the grain of thought as with other languages.

So this was then followed by reflection and Q&A session, bringing us to the end of introductory session on धातुरहस्य.

Erudite Erlang!

Tags


This October, I had the opportunity to learn Erlang at a pre-conference workshop – Deep Dive into Erlang Ecosystem by Robert Virding, one of the co-creators of the language during Functional Conference 2016, Bengaluru. Many things surprised me, especially the philosophy behind letting things fail, no custom data-types to facilitate upgrading things while the system is running, share nothing, massively scalable etc… all baked into the language and down below till the VM. Erlang is a functional language, though it did not start out to be one. It evolved to it. The same applies to the Actor model in Erlang as well. All these got introduced in the language to solve real-world problems and the simplicity with which these things got approached.

John Hughes in his paper – Why Functional Programming Matters highlights that structuring software using complicated scope rules, separate compilation units are help only with clerical details for modularisation. However, the two great features of functional languages, Higher-Order Functions (HOFs) and Lazy Evaluation (Separating generation and selection) contribute significantly to modularity. Additionally, in my view, Erlang brings the modularity of functions to processes to the above. This takes modularity to runtime, where a function can become a first-class process. You don’t have to do anything special to that function, by simply using spawn call, a function can run in a separate process. Thus, partitioning of the application based on load becomes dynamic. This axis of modularity does not pervade through the physical structure while organising the code. This is really a big thing to me.

I’ll jot down a few things that I managed to scribe during the workshop. Robert started with Sequential Erlang, followed by Concurrent Erlang:

Sequential Erlang

LANGUAGE:

  • No equivalence for nulls in Erlang.
  • No Character data-type.
  • No proper string data-type. Just list of characters and shell presents pretty-printed string – a syntactic sugar. For example – [$H, $e, $l, $l, $o]. prints "Hello"
  • Atoms (concept borrowed from Prolog) – Its value is itself. They are constant literals.
    • For example – foo. is an atom that points to itself foo.
    • They are unique, only one in the system with the name foo.
    • For example – all module names, function names are atoms.
    • c(sample) prints tuple {sample, ok} is also an atom.
    • All atoms are stored in atom table (size about 1 million).
    • You can convert atom_to_list(foo).
    • When to use atom? If you do things dynamically, you have to be very careful not to use it.
    • Converting list_to_atom("123"). gives '123'
  • You cannot create new data-types in Erlang.
    • A common convention to create a data-type is to create a tuple with first element as the type name. For example – {person, 'Joe', 'Armstrong'}
    • There are no constructors. The act of creating data structure is writing data itself.
    • So, if you want to create a type, you can use the first element in the tuple to be a type discriminator atom. For example –
               % define a square with side 10
               S = {square, 10}.
               % define a circle with radius 20
               C = {circle, 20}
               % define a triangle with length of 3 sides
               T = {triangle, 10, 20, 30}
               
  • Erlang is functional. All Data is immutable. Its all the way down to Erlang VM. Many things are implemented at VM level, because its very fundamental.
  • Variables cannot be re-bound. Variables beginning with _ are special (called don’t care variable)
  • There are no global variables. Erlang does not share data, there is no global data and no mutation of data is allowed.
  • 13> A.
    * 1: variable 'A' is unbound
    14> A = 1.
    1
    15> A = 2.
    ** exception error: no match of right hand side value 2
    16> A.
    1
    

    To forget the value of A. (It works only in a shell, not in a function)

    17> f(A).
    ok
    18> A.
    * 1: variable 'A' is unbound
    19> A = 2.
    2
    20> A.
    2
    

PATTERN MATCHING:

  • = is a pattern match operator. This is the second big thing. It should not be confused with assignment. So, A = 10 is pattern matching. The general structure is – Pattern = Expression.
  • Expression cannot contain unbound variables.
  • Lists. List = [element | List] or []. Cons operator is – |. For example –
    21> [1 | []].
    [1]
    22> [1 | [2, 3]].
    [1,2,3]
    23>[Head|Rest] = [1, 2, 3, 4].
    24>Head.
    1.
    25>Rest.
    [2, 3, 4].
    26>[H|T] = [].
    ** exception error: no match of right hand side value []
    
  • Erlang is probably the only language where you have binary pattern matching and pattern matching on bitstrings. This makes it easy to grab parts of a binary packet and do validations on them.

FUNCTIONS:

  • Always prefix module names, don’t import entire module. module:function is the way it can be called.
  • Declaring function example –
         circumference(R) -> 
            2 * math::pi() * R
       

    Write variables with upper-case, example R in above case, if you use lower-case, it becomes an atom and not treated as a variable.

  • Also product(X, Y) -> X * Y. and product(X, Y, Z) -> X * Y * Z. are different functions.
  • You can do multiple dispatch based on patterns matched. For example –
          area({square, Side}) -> 
             Side * Side;
          area({circle, Radius}) -> 
             3.14 * Radius * Radius;
          area({triangle, A, B, C}) ->
             math:sqrt(S*(S-A)*(S-B)*(S-C)).      
        

As it is said, two most difficult things in computer science is naming and doing distributed computing. Erlang has lambdas to handle the naming and for distributed computing, it has built-in support.

MODULES:

It is a construct that allows related functions to be grouped together.

  • Module name has to be same as file name. Store “`demo“` in “`demo.erl“`.
  •     -module(demo). % This is the first directive
        -export(double/1) % exportable functions
        
        double(X) ->
          times(2, X).
       
        % private function
        times(X, Y) ->
          X * Y. 
        
  • Exported functions can be called from outside the module. In the above case double is exported. The function name is followed by its arity, in our case the function double has arity 1.
  • Unexported functions have private visibility.
  • Upgrade while the system is running is one of the key principles behind reloading modules. This is one of the reasons why Erlang does not have user-defined types because they will come in the way of hot-loading of the modules.

NODES:

An Erlang node is composed of many Erlang Processes. An Erlang Process is not an OS level process. However, Erlang system is an OS process. For example, to start 2 Erlang systems – on the shell prompt, you can say

$ erl -sname foo
$ erl -sname bar
  • An Erlang System can spawn millions of Erlang Processes.
  • Things that are shared in an Erlang System across Erlang Processes are –
    • There is one atom table per Erlang System and
    • they all see the same code.
  • You send messages across Erlang Processes. Two Erlang Processes also communicate by sending messages, its PID etc.. and then marshal/unmarshall data across processes. You don’t need marshalling/unmarshalling across Erlang Processes.

EXCEPTIONS:

Erlang is big on errors. There is no defensive programming in Erlang. System is designed to handle errors. Whenever an exception occurs, instead of handling the exception, Erlang lets its process crash and starts a new one in a hope that it can take care. It died and I restarted. This is fundamentally a different way of thinking about handling exceptions. When you start handling exceptions, the client code gets polluted with lot of exception handling. Erlang is not scared of crashing Erlang processes. So, if an exception occurs, the Erlang Process is killed, not the whole Erlang System. Closest Metaphor that I can think of is: each Erlang process is like a cell in the body, if one dies, create a new one.

At any given time you can check the processes running in an Erlang system by-

45> processes().
[<0.0.0>,<0.1.0>,<0.4.0>,<0.30.0>,<0.31.0>,<0.33.0>,
 <0.34.0>,<0.35.0>,<0.36.0>,<0.38.0>,<0.39.0>,<0.40.0>,
 <0.41.0>,<0.42.0>,<0.43.0>,<0.44.0>,<0.45.0>,<0.46.0>,
 <0.47.0>,<0.48.0>,<0.49.0>,<0.50.0>,<0.51.0>,<0.52.0>,
 <0.53.0>,<0.146.0>]

Concurrent Erlang

CREATING PROCESSES:

Everything in Erlang is a process, in fact, IO is also a process. One has to design SRP compliant processes. You can group related processes under a supervisor. To create a process, you use spawn and it returns a process Id, the syntax is – Pid = spawn(Mod, Func, Args). For example:

49> spawn(sample, add, [2, 3]).
<0.159.0>
50> Pid = spawn(sample, add, [2, 3]).
<0.161.0>
51> processes().
[<0.0.0>,<0.1.0>,<0.4.0>,<0.30.0>,<0.31.0>,<0.33.0>,
 <0.34.0>,<0.35.0>,<0.36.0>,<0.38.0>,<0.39.0>,<0.40.0>,
 <0.41.0>,<0.42.0>,<0.43.0>,<0.44.0>,<0.45.0>,<0.46.0>,
 <0.47.0>,<0.48.0>,<0.49.0>,<0.50.0>,<0.51.0>,<0.52.0>,
 <0.53.0>,<0.146.0>]
  • Message Passing is the only way in which processes can communicate.
  • Sending is asynchronous and Receive is selective and suspend. Matched messages against pattern are removed and executed whereas Unmatched messages are left in the queue. There is a tool called Wombat which can monitor Erlang System queues and one can define a threshold.
  • When a process dies, its message queue and everything else associated with it also dies.
  • A process can have multiple receive...end blocks.
  • A module has many functions and each function can run in its own process. There is no way to tell by physical inspection, except by reading code and knowing which function runs in different process.
  • spawn can create processes on other nodes, not just within the local node.
  • You don’t have to use Pid, you can instead use Registered Name, an Alias for that Pid.
  • Return Success and Error value as a tuple. For success: {ok, Result}, for error: {error, Reason} and for timeout: {error, timeout}.
  • Don’t forget to remove messages from the queue after the timeout occurs.

So, the general Process Skeleton is –

  1. Initialize, Loop, Terminate.
  2. Managing state: You carry state along. Produce new state after each operation and carry that along.

For Tracing, one can use observer:start(). to look at the Graphical Interface for Tracing and other details.

SUPERVISORS:

You can group related processes under a supervisor. Supervisor trees can be created and have a top-level supervisor. If you kill the supervisor, and it will kill all the children. If you kill the child then it will keep re-starting. gen_server is an implementation is a generic server implementation. It has callbacks that you plugin.

ERLANG ECOSYSTEM:

  • Test Tools – Eunit and CommonTest
  • Erlang Build Tool – Rebar3 – It can run Eunit tests.
  • Languages – Many languages available to code in: Elixir, LFE
  • Mnesia – Distributed Database

USING ERLANG:

  • Takes time to get in new features/things in the language.
  • Typically takes 1-3 releases to stabilize. Normally, 1 release per year.
  • Its backward compatible.

Looking at all of the above, I can say that elephants can cope up with Erlang and it will make them dance too ;).

What is Erlang good at and not good at?

Its strength are: Concurrency, Fault Tolerence, and Scaling. It can very nicely be used for soft real-time systems. However, it is not efficient at doing numerical calculations, sharing things etc… Use Erlang as a concurrent glue between parts of the same system. Because different parts of the system have different requirements. You can use a Java program to talk to database/numerical calculation and you can use Erlang System that can front-end the world and talk to Java behind the scenes.

Well, there is more to Erlang, you can start exploring on your own. This post was just meant to be an inspiration and a journal for me!

Listening to Om Allah Om…by Pandit Jasraj


Lately, I’ve been listening to this mesmerising rendition of Om Allah Om… in Raga Bhairav by Pandit Jasraj. Thanks to Parjanya Bhatt for sending this link across. I don’t have words to express it, but I’m quite sure it will transport you to a different realm.  I get goose bumps, it stops all activities within me and makes me meditative!