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...

*** 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)
    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},
    lines([BottomLeft,TopLeft,TopRight,BottomRight]) ->
      %clockwise lines in a box
    -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
    mark_box(Box,_,_,_) -> Box.
    signBox(MBox = {box,MLines,_}, Player) ->
      case fourth_side_complete(MBox) of
        true -> {box,MLines,Player};
        false -> MBox  
    % 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),
    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)
    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 -> 
    join_dots({X1,Y}, {X2,Y}) when abs(X2-X1) == 1 -> 
    join_dots(_, _) ->
  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]),
      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)
    continue_play(Players = [P|Ps], G, RandF) -> 
      io:format("~p playing...~n", [P]),
      {NextG, SamePlayerTurn} = turn(P, G, RandF),
      case SamePlayerTurn of 
        true -> 
          io:format("~p taking another turn!~n", [P]),
          play(Players, NextG, RandF);
        false -> 
          play(lists:append(Ps,[P]), NextG, RandF)
    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])
      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)
    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)
    distance({X1,Y1}, {X2,Y2}) -> 
    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) ->
      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)]]),
    -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, []}
    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]) ->
      end, RasterLines).
    draw_row_lines(Lines) ->
      lists:foreach(fun(Line) -> 
        case align(Line) of
          horizontal -> io:format("+---");
          horizontal_blank -> io:format("+   ")
      end, Lines),
    draw_col_lines(Lines) ->
      lists:foreach(fun(Line) -> 
        case align(Line) of
          {vertical_blank, first_column} ->     
            io:format(" ");
          {vertical, first_column} -> 
          vertical_blank -> 
            io:format("    ");
          vertical -> 
            io:format("   |");
          {vertical, TakenBy} -> 
            io:format("~3s|", [TakenBy])
      end, Lines),
    align({Line, vertical_first_col, _}) ->
      case Line of
        {line,_,_,false} ->
          {vertical_blank, first_column};
        {line,_,_,true} ->
          {vertical, first_column}
    align(LInfo = {_, vertical_right, TakenBy}) ->
      case LInfo of 
        {{line,_,_,false},_,_} -> vertical_blank;
        {{line,_,_,true},_,[]} -> vertical;
        {{line,_,_,true},_,TakenBy} -> {vertical, TakenBy}
    align({Line, horizontal, _}) -> 
      case Line of
        {line,_,_,false} -> horizontal_blank;
        {line,_,_,true} -> horizontal
  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

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!


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


  • 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.
    15> A = 2.
    ** exception error: no match of right hand side value 2
    16> A.

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

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


  • = 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 | []].
    22> [1 | [2, 3]].
    23>[Head|Rest] = [1, 2, 3, 4].
    [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.


  • 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}) ->

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.


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.


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.


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().

Concurrent Erlang


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]).
50> Pid = spawn(sample, add, [2, 3]).
51> processes().
  • 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.


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.


  • 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


  • 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!

Mantra Yoga


Continuing from the first day of Spandana 2016 (Intensive Sanskrit Workshop), the second day started with Mantra Yoga – a 45 minute chanting session. This was one of the striking parts of this workshop. Dr. Sampadanandaji took up Mantras from the Rig Veda, the Yajur Veda, and the devotional literature. He explained the meaning of the verses by literal translation and also explained Sri Aurobindo’s psychological interpretation of it.

First things first – How to Chant?
Before beginning the Mantra chanting, Dr. Sampadanandaji made us aware of the important points to be kept in mind while. While chanting, it is important to be careful towards

  • Maintain the short and the long forms – While chanting one cannot make a long short and a short long, else the meaning changes. For example, if the word is दिनमणि (DinaMani), दिनमणि = दिन (Day) + मणि (Jewel), so दिनमणि means Jewel of the day and it is a word used for the Sun. Here all the 4 syllables here are short. But while chanting, if one prolongs the short syllables then it ends up being long, we get the word दीनमणि (DiinaMani), now दीन means Poor. This changes the meaning. So, if the short gets converted to a long or a long to a short, then we will have problems, however, if long is prolonged then we won’t have any issues.
  • Conjunct Consonants – when 2 consonants come together, then one has to apply some stress on them during articulation. For example take the word – आनन्दमयी (Anandamayi), here the conjunction – Nan has to be stressed.
  • Anusvara – the dot above the sound which is the pure nasal sound. For example – take the word रामं (Ramam), some pronounce it as Raman and that’s incorrect.
  • Visarga – the 2 dots besides the character. It is incorrectly pronounced by stressing the prominent ह (Ha) as in aspirated sound. For example, like in ‘aha’ or ‘ihi’. The correct pronunciation is that of a relaxing sound – Ah. One relaxes by giving the air up.
  • Have little understanding of Chandas – the metre in which the mantra is sung. A metre is the physical framework of the verse:
    • Number of lines.
    • Number of words.
    • Arrangement of syllables by short and long.
    • Taking correct pauses.
  • The most important thing is that following the above, one can chant in a technically perfect manner. But, no amount of technical perfection based on the knowledge of the language, the understanding of the chandas, the phonetical correctness can make it complete, if the central element भाव (Bhava) is missing. In the absence of भाव (Bhava), the effect of chanting or prayer will not be there. भवेहि विद्यते देवः तस्माद भवोहि केवलम् means that God exists in feelings, hence in order to get the correct connect, it is only the feelings that matter and not the structure or the grammar.

1. Always begin with ॐ
Finally, every mantra chant begins with the word ॐ (Om) – it is the essential sound because it is the essence of all sounds. Many definitions of ॐ exist, however, The Mother has given a very simple and a powerful definition, She says – “Om is the signature of the Lord”. Every thing in the universe has the stamp of the Divine. With ॐ we can get connected with everything in the creation. Chant ॐ and all will go well. To get the correct articulation of ॐ we need to maintain the 60-40 ratio between O-m, but again, we don’t want to go strictly by this mathematical split, instead go by the भाव (Bhava), the feel.

In the tradition, there is a verse, by which we pay our homage and bow down to ॐ. Using this verse, we began the Mantra Chanting –

ॐकारं बिंदुसंयुक्तं नित्यं ध्यायंति योगिनः ।
कामदं मोक्षदं चैव ॐकाराय नमो नमः ॥

The above verse means – ॐकारं बिंदुसंयुक्तं (Omkaram Bindusamyuktam) means Om with the dot, नित्यं (Nityam) means constantly, ध्यायंति (Dhyayanti) means contemplating, योगिनः (Yoginah) means yogis; So the sentence reads – Om with the dot, one that is constantly contemplated by the yogis.

कामदं (Kamadam) means fulfill all the desires, मोक्षदं (Mokshadam) means liberation, चैव (Chaiva) means and, ॐकाराय नमो नमः (Omkaraya Namo Namah) means salutations to Om again and again. So, the complete sentence would be – fulfills all the desires and liberates, salutations to that Om again and again.

2. शान्ति मन्त्र (Shanti Mantra)
In one of her writings, The Mother has said that there is lot of chaos inside and outside that we need to strongly invoke peace every time. By tradition, the Rishis/Sages have given us the Shanti Mantra –

ॐ शान्तिः शान्तिः शान्तिः

In this mantra, the word शान्तिः (Shantih) is repeated 3 times. This is because the maximum chaos is at the ordinary level of consciousness – at the physical level, at the vital level and at the mental level. When शान्तिः (Shantih) is said 3 times, we are invoking peace in the physical, peace in the vital and the peace in the mental. Rest of the levels of consciousness are already peaceful, however we don’t feel that peace because of the way in which we function and work, that is, at the ordinary level of existence. The Mother says that when you begin anything, you start with this invocation – ॐ शान्तिः शान्तिः शान्तिः She further says that if you do it before and after your food, then the digestion happens properly.

Again, like in every chanting, one has to feel the peace within as well, else its just a mechanical chanting – one that is devoid of feeling. Note that after the word शान्ति (Shanti) there is Visargah and we need to articulate it properly. We don’t articulate it like “Shantihi” – ending with हि (Hi) – “ihi” to be precise; instead the correct articulation would be “Shantih” – releasing or giving up the breath as if one is relaxing and blend the Visargah correctly between 2 शान्ति (Shanti) words (you can replay the above mantra).

3. Shraddha Mantra
Dr. Sampadanandaji then took up a Mantra from the Rig Veda hymn श्रद्धा सुक्तम् (Shraddha Suktam) containing set of mantras – It is an invocation to श्रद्धा देवी (Shraddha Devi)

श्रद्धां प्रातर्हवामहे श्रद्धां मध्यंदिनं परि
श्रद्धां सूर्यस्य निम्रुचि श्रद्धे श्रद्धापयेह नः

What does the word श्रद्धा (Shraddha) mean? It has ranges of meaning – faith, focus, attention, respect, devotion etc… Usually it is used for faith. Srimad BhagvadGita says – श्रद्धावान लभते ज्ञानं (Shraddhavan labhate gynanam) meaning – one who has श्रद्धा (Shraddha) can attain to knowledge.

However श्रद्धा (Shraddha) is not mere faith, let us look at it deeply by starting with the de-construction of the word. Essentially, there are 2 components in the word श्रद्धा (Shraddha) = श्रत् (Shrat) + धा (Dha). धा (Dha) is a root sound, which essentially means – to hold on to, to cling to, or to grasp, to seize, to take, to place. श्रत् (Shrat) etymologically in the traditional interpretation of the Vedas is सत (Sat) and it means Truth. So, श्रद्धा (Shraddha) means holding on to Truth.

Sri Aurobindo when interpreting a mantra which has got the word श्रद्धा (Shraddha) in it says – श्रद्धा (Shraddha) means whatever is true to our aspiration. Let us understand this with an example, say that – one’s central aspiration is the realization of the Divine, and each and every movement of our being must collaborate with that aspiration. If one part within our consciousness does not want to help and says – No; whereas the other part wants to participate and says – Yes, then we will be living in Divided Consciousness and this means we don’t have श्रद्धा (Shraddha). So, श्रद्धा (Shraddha) means that each and every part, each and every movement of our being comes forward to participate and collaborate with the central aspiration. In his book – The Mother, Sri Aurobindo says that if one part of the being says – Yes, while the other part has any hesitation or any shrinking or any reservation then the Truth cannot be realized. Everything and every movement of our being has to be one. So, collaboration of all the movements coming from different parts of our being need to be one with central aspiration and that is called as श्रद्धा (Shraddha). So, when Srimad BhagvadGita says – श्रद्धावान लभते ज्ञानं (Shraddhavan labhate gynanam), it is not to be interpreted as mere faith, instead, the total sincerity of the being is meant by the word श्रद्धा (Shraddha).

Dr. Sampadanandaji pointed out that when one visits Sri Aurobindo’s room on your birthday, while going up the stairs, there is a message – Cling to Truth and this is the exact translation of the word श्रद्धा (Shraddha). So, every part of our being needs to cling to truth, the truth that is central to our aspiration. So the above invocation to श्रद्धा (Shraddha) was most important for the Rishis, because it was the basis of their sadhana and progress, and hence they invoked श्रद्धा (Shraddha) as a deity, as a force.

प्रातर्हवामहे (Pratarhavamahe) = प्रातः (Morning) + हवामहे (we invoke), so प्रातर्हवामहे (Pratarhavamahe) means in the morning we invoke the presence of श्रद्धा (Shraddha) and मध्यंदिनं means Mid-day. So the first sentence essentially means – we invoke the presence of Shraddha Devi in the morning and throughout the mid-day.

सूर्यस्य (Suryasya) means Sun and निम्रुचि (Nimruchi) means setting. Again at the Sunset, we invoke the presence of Shraddha Devi. श्रद्धे श्रद्धापयेह नः means fill us with more Shraddha and Shraddha Devi be founded in us, be seated in us, so that we can proceed on the path of progress. All of us then chanted the above mantra starting with ॐ.

4. Devotional Literature – अधरं मधुरं (Adharam Madhuram)
Dr. Sampadanandji then took up अधरं मधुरं (Adharam Madhuram) is a part of मधुराष्टकम् (Madhurashtakam) composed by Shri Vallabhacharya, dedicated to description of Lord Krishna and created while moved by intense devotion, singing the praises of the Lord. Here Krishna’s beauty is described and he is described as मधुराधिपति (Madhuradhipati) = मधुर (Madhur) means Sweet + अधिपति (Adhipati) means Lord and so मधुराधिपति (Madhuradhipati) means Lord of sweetness.

अधरं मधुरं वदनं मधुरं
नयनं मधुरं हसितं मधुरम् ।
हृदयं मधुरं गमनं मधुरं
मधुराधिपतेरखिलं मधुरम् ॥

अधरं (Adharam) means lips, वदनं (Vadanam) means face, नयनं (Nayanam) means eyes, हसितं (Hasitam) means smile, हृदयं (Hridayam) means heart, गमनं (Gamanam) means gait/walk/movement. So essentially the verse means that Lord Krishna’s lips are sweet, face is sweet, the eyes are sweet, smile is sweet, heart is sweet, gait is sweet and every thing about you is sweet, O Lord of sweetness.

This is composed in the Sanskrit metre called तोदकम् (Todakam). The above verse has 4 lines and each line has 12 syllables. The arrangement of the syllables is in the pattern – SSL, where S = Short Syllable and L = Long Syllable. There are 2 Short syllables followed by 1 Long syllable. This pattern repeats for 4 times in a line. While singing, one can take a pause after every 6th Syllable. Lets see this arrangement visually –

1 2 3 4 5 6 7 8 9 10 11 12
रं धु रं नं धु रं
नं धु रं सि तं धु रम्
हृ यं धु रं नं धु रम्
धु रा धि ते खि लं धु रम्

This session was then followed by the regular classes. For the second day, we dived on to an introduction to Chandas – The Rhythm of Sanskrit Metrics, which I’ll post next.

Wonders of Sanskrit Alphabets


Continuing from the first post, the post lunch session (the third for the day) started with introduction to Sanskrit alphabets. Also, I would like to thank Dr. Y. N. Rao, for without his recordings, I would have not been able to fill in the gaps in my notes and write this as it stands now.

Just as every language has its own alphabet system, so does Sanskrit. However, in Sanskrit we find a very systematised, highly scientific system of sound arrangement of alphabets. But before that he asked us a question – What is an alphabet? Many of us attempted to answer as –

  • Basic sound
  • Symbol
  • Fundamental syllable
  • Letter

Finding no satisfactory answer, the question changed to – What do we find in an alphabet? We find letters in the alphabet. This lead to another question – What is a letter? A letter represents sound, rather a letter is the smallest unit of sound.

In Sanskrit, alphabets are called

  1. वर्णमाला (Varnamala). Literally speaking, वर्ण (Varna) represents letters and माला (Mala) means a garland. So Varnamala means garland of letters.
  2. अक्षर-समाम्नाय (Aksarasamaamnaaya) – Yet another term in Sanskrit for alphabets. अक्षर (Akshara) refers to letters and समाम्नाय (Samaamnaaya) means tradition, instruction. So अक्षर-समाम्नाय may mean the tradition of or instruction on the basic sounds of the language. Going to the root sounds आम्ना (Aamana) means to repeat, so समाम्नाय means well-repeated or mentioned together. So, composition leads to अक्षर-समाम्नाय meaning – where the basic sounds of the language are well repeated or mentioned together.

But Dr. Sampadanandaji led us to the depths of why these fundamental unit of sounds were called अक्षर (Akshara) or वर्ण (Varna). The word अक्षर = अ (a) + क्षर (Kshara). The अ is negation and prefixed in front of क्षर. क्षर (Kshara) means perishable or to die. So, Akshara means Not Perishable. So, why was this property given to the sound?

For this Modern Physics has its own theory and Indian Meta-Physics has its own. As per Indian Meta-Physics, the moment a स्पन्द् (Spanda) means Vibration is created, it is imperishable. The moment one thinks, one creates vibration. Once created the sound of vibration is permanent, it never dies, it does not decay, instead it gets absorbed in the आकाश (Akasha) means Space and it remains there*. So the स्पन्द् is imperishable. This realisation of the Sages and Rishis resulted the word Akshara, attributing the imperishable property of sound. It refers to the philosophy of शब्दो नित्यः (Shabdo Nityaah) means the eternity of sounds. However, the word अक्षर (Akshara) got confined to the speech sounds, the fundamental sounds of the language. Again, I would like to emphasize that, Akshara is not the gross sound that we hear, listen, spear or write, it essentially means स्पन्दन (Spandana) or vibration.
* My additional note, we often find the words like Akashic Records in books, this in-turn means that Akasha is a huge repository (infinite memory) of information.

Why is it called वर्णमाला (Varnamala)? There are 2 ways to look at this. वर्णमाला comes from the root sound वर्ण (Varna). Varna means to describe. Varna also means color. For example, पीतवर्ण (Pitavarna) means yellow color or रक्तवर्ण (Raktavarna) means red color. It is about looking at the sounds as color packets. This again is from the realisations of ancient rishis wherein the deeper philosophy is about the gradation of the sound. At the gross-most level, what we humans speak, is the gross sound. In order to grasp sound in its truest sense, one needs to have access to subtler levels. According to Tantric scriptures, at the subtlest level, it is called परा वाक् (Para Vak) means the Supreme Speech, that which is bright, effulgent, shining without any color. When sound descends down to become gross speech, it absorbs colors on the way. Here they saw the connection of sound with light and described it so, both at the subtlest and at the grossest levels. So, light is not free from sound and sound is not free from light. In their experience, they saw that a particular sound had a particular quality of a color and hence they associated sound with color. Also, if one looks at Sanskrit dictionary, and find out all about the root-sounds referring “to sound” – they also refer to light. One will find sound and light described together in root sound. One cannot separate sound and light. As sound was also seen associated with different colors the word Varna is used.

There are 48 basic sounds in Sanskrit alphabets. Like any other language, in Sanskrit these sounds are categorised into vowels and consonants. Dr. Sampadanandaji asked us to define what are vowels and consonants sounds? Many of us answered this as –

  1. Vowels are independent sounds.
  2. Consonants are dependent sounds.

However, Dr. Sampadanandaji pointed out that there is a problem with this definition, using this definition one cannot distinguish between all the vowels and consonants in other foreign languages. Lets say, we ask someone to speak/sing out all the alphabets of a language not known to us, how will you (not knowing that language) then be able to distinguish between vowels and consonants using the above definition? However, Sanskrit offers a specific way to differentiate them. The terminology used for vowels is अस्पृष्ट (Asprushta) means Untouched. स्पृष्ट (Sprushta) means touched and prefixing अ before स्पृष्ट negates it – so अस्पृष्ट means untouched. So, it essentially refers to the sound that is produced without touching any part of the speech producing organ. So, sound without any contact is a Vowel Sound. For example – अ (a). Whereas, consonants are called स्पृष्ट because they are produced by contact with some part of the mouth, either tongue or lips. For example – ब (Ba). Vowel sounds are free flowing sounds and one can intone it, whereas consonants are mute sounds – they cannot be intoned. Using the Sanskrit definitions – अस्पृष्ट for Vowels and स्पृष्ट for Consonants, one can distinguish between vowels and consonants in any language.

Other word used for vowel is स्वर (Svara) and for consonant is the word व्यन्जन (Vyanjana) is used. Svara means स्वयम् राजते (Svayam [itself] Rajate), so स्वर (Svara) means one that shines by itself. Whereas the word व्यन्जन (Vyanjana) means Decoration. Consonantal sounds are the decorative sounds. Vowel sounds are the life of the language and the very soul of the language, therefore called आत्मा (Aatma) means soul, or प्राण (PraaNa) meaning life, whereas consonants can be compared with the body, because body can be decorated. Soul cannot be decorated. Tamil language uses this metaphor for vowels and consonants.

The sounds in Sanskrit are arranged in a particular order and there is logic behind the arrangement of alphabets. You are permitted to ask the question – why this sound comes after that sounds? You have a scientific explanation which satisfies the reasoning mind. On the side 😉 – Can anyone explain the logic in the arrangement of alphabets in English language?

The entire arrangement of sounds in Sanskrit is based on the following:

  • The place of its production or pronunciation.
  • The effort required to produce it.
  • The duration for which it is produced.
  • The quality of the sound.

When we recite a sound, the air gets translated to sound. When air moves out through the vocal chord, it can be obstructed at different places in the mouth to produce speech sounds. However, one cannot obstruct the air at any position in the mouth where one pleases and generate a sound. There are possible positions in the mouth where the air can be obstructed. The first possible position where the air can be obstructed is from where one produces – क (Ka) ख (Kha) ग (Ga) घ (Gha) ङ (ṅa). These sounds are also referred to as Guttrals. At this position, the जिव्हा मूल (Jivha Mula) means the root of the tongue comes in contact with मृदु तालु (Mridu Taalu) means the soft palate and obstructs the air flow. It is not possible to obstruct the flow of air below this position by any human being. Therefore, क (Ka) is not only the first consonantal sound in Sanskrit, but also for the humanity.

The second possible position is from where the consonants – च (ca), छ (cha), ज (ja), झ (jha), ञ (ña) are produced. At this place, the air is obstructed when the upper middle of the tongue comes in contact with the back of the hard palate. There is space between the first and second positions, however, its not possible to obstruct the air in that space.

The third possible position is from where we say – ट (ṭa), ठ (ṭha), ड (ḍa), ढ (ḍha), ण (ṇa). The tongue is rolled back to touch its tip to the middle hard palate. They are also referred as Retroflexes.

The fourth possible position is from where we say – त (ta), थ (tha), द (da), ध (dha), न (na). Here the tip of the tongue touches back of upper teeth when producing these consonants. They are also referred as Dentals.

The fifth possible position is from where we say – प (pa), फ (pha), ब (ba), भ (bha), म (ma). Here both the lips are pressed together. They are also referred as Labials.

The consonants are tabulated below summarizing the above partly (There is more to the table that we’ll see later).

Given below are not pure consonantal sounds. Pure consonantal sounds cannot be produced without the vowel sounds. For example, क (ka) = क् (k) + अ (a), ख (kha) = ख् (kh) + अ (a) and so on…

अल्प प्राण
Alpa Prana
Minimum Release
महा प्राण
Maha Prana
Maximum Release
अल्प प्राण
Alpa Prana
Minimum Release
महा प्राण
Maha Prana
Maximum Release
release from
Cavity (Oral)
Cavity (Oral)
Cavity (Oral)
Cavity (Oral)
Mouth &
Nasal Cavity (Oro-Nasal)
Vocal chord Contracted Expanded Contracted Expanded  
Place of
Refer to the figure here. I have retained the same color coding used therein.
Guttrals क (ka) ख (kha) ग (ga) घ (gha) ङ (ṅa)
Palatals च (ca) छ (cha) ज (ja) झ (jha) ञ (ña)
Retroflexes ट (ṭa) ठ (ṭha) ड (ḍa) ढ (ḍha) ण (ṇa)
Dentals त (ta) थ (tha) द (da) ध (dha) न (na)
Labials प (pa) फ (pha) ब (ba) भ (bha) म (ma)
Consonant quality Hard (कठोर) Soft (मृदु) and Loose Vocal Chord

Now, consider the first row, क (Ka) ख (Kha) ग (Ga) घ (Gha) ङ (ṅa). These are produced from the same position, that is, Guttral. What makes all of them different? How is क (Ka) different from ख (Kha)? More air is released when we recite ख (Kha), whereas less air is released when क (Ka) is recited. So, sound क (Ka) is produced with minimum breath release whereas ख (Kha) is produced with maximum breath release. In other words, क (Ka) is contracted and ख (Kha) is expanded. This is like concentration and meditation. This play of contraction and expansion is repeated again in ग (Ga) and घ (Gha). In Sanskrit, the sounds that are produced with minimum breath are called अल्प प्राण (Alpa Prana) and the ones that are produced with maximum breath are called महा प्राण (Maha Prana). In all the 4 sounds that we saw, the air was released through mouth and the nasal cavity was closed. If the air is allowed to pass through the nasal cavity and the mouth simultaneously, the fifth sound ङ (ṅa) is produced from the same position. However, this is not pure nasal sound. All the sounds in the fifth group – ङ (ṅa), ञ (ña), ण (ṇa), न (na) and म (ma) are referred to as अनुनासिक (Anunasika) or मुख-नासिकवचन (Mukh-nasikavachan) मुख means mouth, नासिका means nose and वचन means expression, so मुख-नासिकवचन or Oro-Nasal expressions/sounds as both mouth and nose need to be open simultaneously when reciting these sounds. It is not possible to produce these 5th group sounds by opening either the mouth or the nose, both need to be open simultaneously. Experiment and verify it for yourself 🙂

Dr. Sampadanandaji pointed out that, if anyone has the problem of Sinusitis, then just repeating these 5th group Oro-Nasal sounds for continuous period of 3 months can get rid of it.

Now, if you look at any consonant row in the above table (from left to right), first you have अल्प प्राण (Alpa Prana) sound followed by महा प्राण (Maha Prana) followed by अल्प प्राण (Alpa Prana), followed by महा प्राण (Maha Prana) and finally followed by simultaneous release of air through Oral and Nasal cavities. If you very slowly and consciously repeat these sounds you will find that there is an in-built system of Pranayama in the alphabets itself. If you recite these alphabets starting from अ (a) to ह (Ha), Pranayama takes place and it begins the healing process. There is a tradition in India, where people just keep chanting these alphabets and nothing else; alphabets chanting is the mantra for them and they chant them in various ways.

Next, what is the difference between the 2 pairs of sounds – क (Ka) ,ख (Kha) and ग (Ga), घ (Gha)? If you put your fingers below your chin or on your double chin, if you have one ;), then recite you क (Ka) ,ख (Kha) and then recite ग (Ga), घ (Gha). You will observe that when reciting ग (Ga), घ (Gha), the vibrations are more as compared to recitation of (Ka) ,ख (Kha). In the case of ग (Ga), घ (Gha), the vocal chord is loose and results in more vibrations. First 2 sounds of each row – क (Ka) and ख (Kha), च (ca) and छ (cha), ट (ṭa) and ठ (ṭha), त (ta) and थ (tha), प (pa) and फ (pha), there is harshness in these sounds and therefore are called कठोर or Hard Consonants whereas the rest of the consonants (except Sibilants) and Vowels are मृदु or soft in nature.

In Sanskrit, there are 13 Vowels – अ (a), आ (aa), इ (i), ई (ii), ऋ (ṛ), ॠ (ṝ), लृ (ḷ), उ (u), ऊ (uu), ए (e), ऎ (ai), ओ (o), औ (au).

Of these 13, 9 are Basic Vowel sounds, they are – अ (a), आ (aa), इ (i), ई (ii), ऋ (ṛ), ॠ (ṝ), लृ (ḷ), उ (u), ऊ (uu). What we saw for consonants earlier, applies to these vowel sounds as well, i.e – place of pronunciation, duration, quality etc…

Duration Short (Blink eyes or Snap fingers Once) Long (2 x Short)
Place Of
Refer to the figure here. I have retained the same color coding used therein.
Guttrals अ (a) आ (aa)
Palatals इ (i) ई (ii)
Retroflexes ऋ (ṛ) ॠ (ṝ)
Dentals लृ (ḷ) you can have long form of it, but no word is found yet that uses it
Labial उ (u) ऊ (uu)
Vowel quality Soft

In the table above, the duration refers to the time required to produce the vowel sound. The short form can be spoken in the same time as the time required to either blink the eye or do a छोटिका (Snap) of fingers. The long form is twice the duration of short form.

Mixed Vowels
ए (e), ऎ (ai), ओ (o), औ (au) are not pure vowel sounds, they are called mixed vowel sounds, because they are produced by combining basic vowels. They are called सन्ध्यक्षर् (Sandhyakshara) or diphthongs. Sandhyaksharas are always long in duration.

  1. अ/आ (a/aa) + इ/ई (i/ii) = ए (e)
  2. ऎ (ai) is a further modification of ए (e)
  3. अ/आ (a/aa) + उ/ऊ (u/uu) = ओ (o)
  4. औ (au) is a further modification of ओ (o)

There are 4 semi-vowel sounds – य (ya), र (ra), ल (la), व (va). इ (i) is the corresponding vowel sound of the semivowel य (ya). ऋ (ṛ or ri) is the corresponding vowel sound of the semivowel र (ra). लृ (ḷ or Lri) is the corresponding vowel sound of the semivowel ल (la). ऊ (uu) is the corresponding vowel sound of the semivowel sound व (va). These sounds are obtained by adding अ (a) to ई (ii), ऋ (ṛ), लृ (ḷ) and ऊ (uu) respectively. These are also called ईश स्पृष्ट (Isha Sprushta) means Mild Contact.

Important Vowels Summary

  1. Among all the vowel sounds – अ (a), इ (i), उ (u) are the Simple Vowels, having their respective long forms – आ (aa), ई (ii), ऊ (uu).
  2. ऋ (ṛ), ॠ (ṝ) and लृ (ḷ) are not pure vowel sounds there is a little mix up of consonantal sound. We studied them from the place of pronunciation above, however, the traditional way of arranging vowels is such that Pure vowels are first – अ (a), आ (aa), इ (i), ई (ii), उ (u), and ऊ (uu) followed by – ऋ (ṛ), ॠ (ṝ) and लृ (ḷ) to show visually some mix up of consonantal sound.
    अ (a) आ (aa) इ (i) ई (ii) उ (u) ऊ (uu) Pure Vowels
    ऋ (ṛ) ॠ (ṝ) लृ (ḷ) Vowels with some mix up of Consonantal sounds
  3. Finally, ए (e), ऎ (ai), ओ (o), औ (au) these are Diphthongs (Combined Vowel Sounds)

Having finished the vowels, we will now look at what are called as Hissing Sounds. There are 3 distinct ones.

Sibilants श (Sha) ष (Ṣa) स (Sa)
Place of pronunciation Palatal Retroflex Dental
Experiment Take the tongue to the respective positions and hiss from there, you will get all the 3 sounds.
Consonant type Hard

Sibiliants are also called as उष्म वर्ण (Ushma Varna), because they produce heat (hot air comes out) when they are articulated.

Finally, the last sound is ह (Ha), is Guttral and here we have the maximum breadth release.

In the tantric tradition, the entire human body is conceived as a शब्द शरीर (Shabda Sharir) शब्द means sound and शरीर means body, so शब्द शरीर means sound body. It is called so because of the flow of प्राण (Prana) means the Life-force or Life-energy through different channels or nadis (72,000 of them) in the body. The movement of the Prana generates sounds. These sounds are created in our system all the time. They are heard by the tantric sages, seers, practitioners in their meditation. That is why, in the tantric scriptures we find the location of these sounds in the human body. They gave names to these locations based on the number of energy currents.

  1. The place where 2 energy currents meet is called as सन्धि (Sandhi).
  2. The place where 3 energy currents meet is called as मर्म (Marma). There are about 52-55 मर्म स्थान (Sthana) means location in the body and each location has its own sound. In the rituals, when they do अङ्ग स्पर्श (Anga Sparsha) अङ्ग means body and स्पर्श means touch, they touch different मर्म स्थान in the body. For example, using the sound they touch the eyes or ears; doing this purifies and energises those locations.
  3. The place where more than 3 energy currents meet is called as चक्र (Chakra). This is where the sound is more obvious. Specific sounds are assigned to different chakras. When one recites those sounds or mantras, it purifies and energises that Chakra.

In the tantric scriptures, when they conceived the human body as शब्द शरीर, they called an individual – अहम (Aham). अहम means it starts with अ (a) and ends with ह (Ha). So, an individual comprises of everything between अ (a) and ह (Ha), both inclusive. म (Ma) is added to make it a proper verb, hence the word अहम (Aham) means “I”.

Dr. Sampadanandaji pointed out that when ह (Ha) is combined with the seven special alphabets – ण (ṇa), न (na), म (ma), य (ya), र (ra), ल (la) and व (va), then one gets a completely different experience with it when articulated correctly.

  1. ह (Ha) + ण (ṇa) = ह्ण (Hṇa)
  2. ह (Ha) + न (na) = ह्न (Hna)
  3. ह (Ha) + म (ma) = ह्म (Hma)
  4. ह (Ha) + य (ya) = ह्य (Hya)
  5. ह (Ha) + र (ra) = ह्र (Hra)
  6. ह (Ha) + ल (la) = ह्ल (Hla)
  7. ह (Ha) + व (va) = ह्व (Hva)

If one repeats the above set for more for than 25 cycles, an individual can start sweating. This is because it makes natural कपालभाति (KapalaBhati). It is also very good for clearing the throat and other throat related problems. These 7 sounds are known as उरस्य (Urasya). उरस (Uras) means the chest and lungs, so उरस्य (Urasya) means belonging to lungs. ह (Ha) sound comes from the lowest depths, and by combining it with the 7 sounds, it further extends the depth.

There are many words in Sanskrit that are उरस्य (Urasya). For example, when saying the word ब्रह्मा (Brahma), many (including me) pronounced it incorrectly as Bramha. मध्याह्न (Madhyahna) means Midday.

Visargaha ः
ः – is a peculiar sound in Sanskrit. It is not to be articulated as अः (Aha) and it is incorrect. Just articulate it by release of breath like when relaxing and it will come out correctly. Visargaha means release, release of the air, or विसर्जन (Visarjana) means give it up. It is the most relaxing sound.

From the Pranayama point of view, Visargaha does बाह्य कुम्भक (Bahya Kumbhaka) where one releases the air and then holds outside. बाह्य कुम्भक improves the power of concentration. One can combine Visargaha with all the Vowels and do this practice to improve concentration – अः (Aḥ), आः (Aaḥ), इः (iḥ), ईः (iiḥ), उः (uḥ), ऊः (uuḥ), एः (eḥ), ऐः (aiḥ), …and so on.

Anusvara ं
अनुस्वारः (Anusvara) is the only pure nasal sound in Sanskrit. It is spoken with mouth closed and the breath is completely released from the nose. When articulated properly, it causes vibrations to start on the forehead between the two eyebrows.

Dr. Sampadanandaji pointed out that, from Pranayama perspective, when you combine the vowel sounds with Anusvara, you get Brahmari Pranayam automatically. For example – अ (a) + ं = अं (Aṃ)

Devanagari Script
Why a particular sound is written in a particular form? This question led to the explanation of Devanagari Script.

If you look at the whole history, from Brahmi onwards the letters were not in the pure form as you see them now. They have been worked out. At present, the symbols that we see in the Devanagari Script are the most beautiful symbols and the way we write Devanagari characters – its a pattern. To create each pattern, it needs a movement and the patterns of Devanagari symbols have a deeper connection with Universal rhythmic movement. Hence each symbol here is an auspicious symbol.

Every letter in Devanagari has presence of 2 lines

  1. Horizontal Line called शिरोरेखा (Shirorekha) on top representing the Universal
  2. Vertical Line represents the Individual. The vertical bar that we see can be on the side as in ख (Kha), the middle as in क (Ka), and ङ (ṅa) it is at the top.

So the connection between the Universal and the Individual is present in the symbols.

To create conjunct consonants, we remove the vertical line and connect the two consonants. For example, to connect न (Na) and य (Ya), we remove the vertical line from न (Na) and attach it to य (Ya) to give न्य (Nya)

Session 4: Sambhasanam

In this session, we got introduced to 2 more words –

  1. अत्र (Atra) means here.
  2. तत्र (Tatra) means there.

Example usage in sentences of daily use –

  1. लेखफलकम् अत्र अस्ति (The writing board is here).
  2. समयसूचिका तत्र अस्ति (The clock is there).
  3. मार्जनी अत्र नास्ति (The duster is not here).
  4. मम मित्रं धवलः तत्र अस्ति (My friend Dhaval is there).
  5. द्वारम् अत्र अस्ति (The door is here).
  6. किं वातायनं तत्र अस्ति (Is the window is there?) आम वातायनं तत्र अस्ति (Yes, the window is there).
  7. अत्र सैकतं तत्र समुद्रः (The sand bank is here, the sea is there).

It is important to note that there are no punctuation marks in Sanskrit. So, you will not find commas, semi-colons or question marks. The only punctuation marks in Sanskrit are and . In Prose, represents पूर्णविराम (PurnaViram), essentially is Phrase Separator. In Poetry, represents पूर्णविराम (PurnaViram) and represents अर्धविराम (ArdhaViram) means Half Pause.

We then got introduced to 3 more words –

  1. कुत्र (Kutra) means where
  2. अन्यत्र (Anyatra) means elsewhere
  3. सर्वत्र (Sarvatra) means everywhere

Examples of daily use in sentences

  1. तव भ्राता कुत्र अस्ति (Where is your brother?) मम भ्राता अन्यत्र अस्ति (My brother is elsewhere)
  2. वायुः कुत्र अस्ति (Where is air?) वायुः सर्वत्र अस्ति (Air is everywhere)
  3. किं अन्धकारः सर्वत्र अस्ति (Is darkness everywhere?) न अन्धकारः सर्वत्र नास्ति (No, darkness is not everywhere)
  4. सर्वत्र किं अस्ति (What is everywhere?) प्रेम सर्वत्र अस्ति (Love is everywhere)
  5. अत्र किं किम् अस्ति (Who who [who all] – are here?) अत्र सर्वम् अस्ति (Everyone is here)
  6. किं हस्ती अत्र अस्ति (Is elephant here?) न हस्ती अत्र नास्ति हस्ती तत्र अस्ति (No elephant is not here, the elephant is there)
  7. धवलः कुत्र (Where is Dhavalah?)
  8. तव अत्र किं कार्यम् (What work do you have here?)
  9. किं सुशीतकम् अत्र अस्ति (Is the refrigerator here?)
    न सुशीतकम् अत्र नास्ति तत्र अपि नास्ति सुशीतकम् अन्यत्र अस्ति (No, the refrigerator is not here, its not also there, its elsewhere)

After listening to the examples, we were asked to frame our own sentences and speak it out to the class.

We then got introduced to a construct यत्र…तत्र (Yatra…Tatra) means where…there. In this construct, यत्र (Yatra) is a Relative Where (it is not a simple Where) and this goes with तत्र (Tatra). Here are the examples –

  1. यत्र जलं अस्ति तत्र मीनः अस्ति (Where there is water, there is fish)
  2. यत्र अनलः अस्ति तत्र धूमः अस्ति (Where there is fire, there is smoke)
  3. यत्र प्राणः अस्ति तत्र जीवनम् अस्ति (Where there is life-force, there is life)
  4. यत्र पाकशाला अस्ति तत्र रोटिका अस्ति (Where there is kitchen, there is roti)
  5. यत्र असत्यं अस्ति तत्र क्लेशः अस्ति (Where there is falsehood, there is misery)
  6. यत्र नेता अस्ति तत्र भ्रष्टाचारः अस्ति (Where there is a politician, there is corruption)
  7. यत्र माता अस्ति तत्र करुणा अस्ति (Where there is mother, there is compassion)

Please note that यत्र…तत्र (Yatra…Tatra) is not to be translated to wherever…there. For wherever, Sankrit has the construct यत्र यत्र… (Yatra Yatra…).

The next lesson for this session was learning about referring to near using ‘this’ and far using ‘that’ . We were introduced to the following words based on the gender that they refer to.

Near (This) Gender
एषः (Eshah) Masculine
एषा (Eshaa) Feminine
एतत् (Etat) Neuter

Example usage would be –

  1. एषः धवलः (This is Dhavalah)
  2. एषा गीता (This is Gita)
  3. एतत् पुष्पम् (This is a flower)

To ask questions, we will ask according to the gender.

Question Gender
कः (Kah) Masculine
का (Kaa) Feminine
किम् (Kim) Neuter

Example usage in sentences will be –

  1. एषः कः (Who is this?) एषः धवलः (This is Dhavalah) धवलः संगणक अभियन्ता (Dhavalah is a computer engineer)
  2. एषा का (Who is this?) एषा सीता (This is Sita) एषा गायिका भाचित्रिका न्यायवादिनी च अस्ति (She is a singer, a photographer and an advocate)
  3. एषः चिकित्सकः (He is a doctor)
  4. एतत् किम् (What is this?) एतत् सङ्गणकम् (This is a computer)
  5. एतत् किम् (What is this?) एतत् प्रक्षेपकम् (This is a projector)
  6. एतत् किम् (What is this?) एतत् चित्रम् (This is a picture)
  7. कः तत्र अस्ति (Who is there?)
  8. किं तत्र अस्ति (What is there?)
  9. किम् एषः तव प्रश्नः (Is that your question?)
  10. किं एषः बालकः तव मित्रं (Is this boy is your friend?) न एषः बालकः न मम मित्रं (No, this boy is not my friend)
  11. किं एषा तव लेखनी (Is this your pen?)
  12. एतत् पुस्तकं अत्र अस्ति (This book is here)
  13. किं एतत् तव स्थानम् (Is this your place?)
  14. मम उपनेत्रं कुत्र अस्ति (Where are my spectacles?)

If you don’t happen to know the gender of the subject in advance, then the general question can be एतत् किम् (What is this?) and the general answer can be एतत् + … , i.e. combination. For example, we know that कर्ण (Karna) is Masculine gender. In case, you don’t happen to know that, you can ask the question – एतत् किम्. In response to that question, there can be 2 possible answers based on the gender of the word कर्ण (Karna):

  1. If you happen to know the gender, you can reply – एषः कर्ण
  2. If you don’t happen to know the gender, then you cannot say – एतत् कर्ण instead you must combine the words like this – एतत्कर्ण , and use as one single word.

The basic word is एतद् (Etad). In Masculine it becomes एषः (Eshah) in Feminine it becomes एषा (Eshaa) and in Neuter it becomes एतत् (Etat). The basic word एतद् (Etad) is never used. In Sanskrit, the word base, whether it is noun or verb base, it is never used. These base words are called धातु (Dhatu) for verbal base and प्रातिपदिक (Pratipadika) for nominal base.

Whereas the words which are derived from the base words by adding suffixes are called पद (Pada) means usable words or ready-to-use words. For the computer folks amongst us, in languages like Java, C++, C# – I’m reminded of the concept of abstract classes which cannot be newified, only meant to be derived from and the non-abstract derived forms can be used or newified.

Dr. Sampadanandaji further answered my question – Why all the interrogative sounds in Sanskrit begin with the sound क (Ka)? Is there a logic to this? He said that to answer this, first we need to understand the nature of question? What does question do? The logic here is that, the sound क (Ka) is the first consonantal sound, it immediately is after the freely flowing vowels and क (Ka) is produced by obstructing the flow of air at the first position in the oral cavity, so it is the first obstruction. Similarly, the nature of question is to stop the free flow of thoughts and hence in Sanskrit, every question begins with the sound क (Ka). In fact, every interrogative pronouns in Sanskrit begins with क (Ka).

Far (That) Gender
सः (Sah) Masculine
सा (Saa) Feminine
तत् (Tat) Neuter

Example usage in day-to-day sentences –

  1. एषः धवलः सः प्रकाशः (This is Dhavalah, that is Prakashah)
  2. एषा गीता सा वर्षा (This is Gita, that is Varsha)
  3. एतद् द्वारं सः दण्डदीपः (This is door, that is tubelight)
  4. एतद् द्वारं तत् वातायनम् (This is door, that is window)
  5. एषः धवलः सा अध्यापिका (This is Dhavalah, that is teacher)
  6. एषः अध्यापकः सः छात्रः (This is teacher, that is student)


Near (This) Far (That) Question Gender
एषः (Eshah) सः (Sah) कः (Kah) Masculine
एषा (Eshaa) सा (Saa) का (Kaa) Feminine
एतत् (Etat) तत् (Tat) किम् (Kim) Neuter

कः (Kah), का (Kaa) and किम् (Kim) has nothing to do with near and far. They are used attributively for What, Which, Who.

  1. कः बालकः सङ्गणक अभियन्ता (Which boy is computer engineer?)
  2. अत्र कः नरः चिकित्सकः (Who is doctor here?) अत्र श्री रावः चिकित्सकः (Here Mr. Rao is a doctor)
  3. अत्र का बालिका नर्तकी (Who is dancer here?) सा नर्तकी (That is the dancer)

Before the session ended, the last lesson was about learning to count from 1 to 10 in Sanskrit. We were made to recite the numbers loud and repeat them.

  1. एकम् (Ekam)
  2. द्वे (Dve)
  3. त्रीणि (Trini)
  4. चत्वारि (Chatvari)
  5. पञ्च (Panch)
  6. षट् (Shat)
  7. सप्त (Sapta)
  8. अष्ट (Ashta)
  9. नव (Nava)
  10. दश (Dasha)

Dr. Sampadanandji ended the day by saying पुनर्दर्शनाय (PunarDarshanaya). The next day started with Mantra Yoga session.

Intensive Sanskrit Workshop – Day 1, First Half @ Sri Aurobindo Society


Yesterday I returned from Pondicherry after attending a 7 day Intensive Sanskrit Workshop at SAFIC, Sri Aurobindo Society, very fulfilled! All the sessions were excellently taught by Dr. Sampadananda Mishra, Director of SAFIC.

Spandana Jan 2016

स्पन्दन (Spandana) for Beginners (Jan 2016)

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, if you are starting to learn Sanskrit. However, as I’m a beginner, 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 has already corrected this post.

First session was Introductions, each participant explained the meaning behind their name and then Dr. Sampadananda Mishra added to it if anyone fell short of explaining theirs.

Session 1: Understanding the Power of Sanskrit
This was the next session that we dived into, a sort of whirlwind introduction to the language. Dr. Sampadananda Mishra explained that each and every word in Sanskrit is conscious of its origin. Sanskrit has (and in general every language) a simple form and a complicated form. The idea in this workshop is to learn the simple form. Having said that it does not mean that Sanskrit is simplified, but its about learning simple Sanskrit, that is, by going back to its origin – the spirit and start learning it from there.

Property Based Language: Other conventional languages are Object-Specific languages, that is, the use of object brings up its picture in the mind. For example, take the word Fan. It immediately brings up its image in mind, it could be a table fan, a ceiling fan or any other fan. The word is used specific to that object. The word fan can have different meanings contextually, but in general it refers to an object. However, in Sanskrit, you are not allowed to have a word that is specific to an object. Does it mean that Sanskrit does not have a word for a Fan or a Tree? Well it does! If it does then how do you say that Sanskrit is not object-specific? An object in Sanskrit has many words. Sometimes even more than 200 words for the same object. So, these synonyms that are used for the same object. Each synonym brings out a specific property of that object and not the object. For example, take the word – Fire. In Sanskrit, Fire is referred by many names – अग्नि, अनल, अपित्तम्, ज्वलनम् (Agni, Anala, Apittam, Jvalanam) and so on…

Now, Lets take the word अग्नि (Agni). The Root Sound in अग्नि is अग् (Ag) – means to move up. It is describing the property of the flame to rise up when it burns. Every word in Sanskrit comes from Root Sound, which is backed by Seed Sound. For this workshop, the scope was limited to Root sounds, Seed sounds are for Advanced workshop (which will be announced later).

Lets take the word अनल (Anala), अनल = न + अलम् and अलम् (Alam) means enough. The न before अलम् negates अलम् and so अनल means not अलम्, which means not enough. Fire burns up everything and yet it asks for more, which is also another property of fire.

Lets take the word ज्वलनम् (Jvalanam), the root sound is ज्वल् (Jval) means to burn, which is yet another property of fire.

Lets take the word शुष्मा (Susma). The root sound is शुष् (Sush) which means dry. It is the property of fire to dry things up.

Thus, it describes the property of the object rather than referring to the object. Sanskrit is a Property-Based language. So, if you have a different experience with the word, you can give it a new meaning and this is exactly what अमरकोश (AmaraKosha) is. It is a online dictionary where you can add new words to it based on your experience. In Sanskrit you are allowed to ask the question – Why अग् (Ag)? Other languages will not permit this.

Another important thing with synonyms is that they are not 100% substitutable by one another. Each synonym has evolved out of a property of that object. The user is left to select the appropriate synonym that brings to the fore the exact property that befits the context.

With Property based languages, there is a shift in thinking towards Properties of the object rather than the object itself. So, why properties? With the focus on properties, we tend to forget about objects, because any object can possess that property. Also, it does not matter whether the object changes the form or appears in a new form and the old forms disappear, because properties are eternal. With property based languages, we can visualise a property-based universe, rather than an object-based universe. As properties are everywhere, they are universal and eternal, whereas objects are impermanent. Sanskrit always deals with that which is eternal and universal. This is why Sanskrit is an eternal language, a universal language. Lets take an example of a plough. In Sanskrit a plough is called हल (Hala). In modern times, we use a tractor whereas in ancient times it was called a plough, so the object has changed. In English, we will use different names for these different objects, but in Sanskrit you can refer to a tractor and a plough by the same name – हल (Hala). हल (Hala) is a word that describes its property/function and not the object.

Now, either a single object or many objects can possess/exhibit those properties. This allows the mind to associate unrelated objects from different contexts having similar properties, however, I would say with Sanskrit, it becomes more than two properties, not just associate, but polysociate (as I would like to call it), essential for the creative energies to fire up and let one’s imagination take-off. Furthermore, we can find out the object that manifests those properties, by inspecting and de-constructing the name. Also, it would not matter whether the same property/properties is/are being fulfilled by multiple objects, we can look-up to any object that does the job.

In my view, learning different languages shapes our thinking and ultimately affects our actions. With Object based languages, an object is the focal point of interaction and so my thinking naturally would tend to be object-oriented and then I’d describe object’s behaviour and properties as if the object owns it. For example, lets say, if we say that the object is a human being, then it can end up critiquing either of us.

I found that Sanskrit’s signal to noise ratio is very good, that is, very high signal, less noise, thus making it very concise. Composing seed sounds to create root sounds and using root sounds to create still larger words and composing words to create still bigger words is at the base of Sanskrit. So, in Sanskrit Composition is THE way to build-up complexity and this composition is governed by rules. This to me is also simple design that we find in computer programming when designing programs. Thinking aloud (I’ve not researched or googled anything on this yet), the program we create is the universe and if we can create a programming language that allows us to express the universe in terms of properties, can we then create Sanskrit-like language to make computer programs or does it already exist? I’m wondering how would that look like? If it exists, is it Haskell? Based on whatever I’ve played with Haskell, the answer turns out be yes, but I’ve yet to use it on a real-life project to be able to confirm. Other languages like Scala, Java8, Groovy, C# span FP and Imperative Programming paradigms (slide 2).

Also from computer programming perspective, composition is THE way to tackle complexity, especially in large software programs, otherwise they have a tendency to become a big ball of mud very quickly. With the ability to compose functions, we can create larger functions and there are rules of composition that we follow. Above 3 and this paragraph is added by me – just being explicit on parts that i’ve added ;).

Now switching the context to Sanskrit back again, lets look at other aspects. Sanskrit is a very beautiful language and beauty comes from order, symmetry and arrangement. All of which are complexity reducing elements. Once complexity reduces, things automatically become beautiful. Lets look at order first. In Sanskrit, if I have to say that my name is Dhaval. I can say it in different ways using the same words and it does not change the meaning of the sentence. For example –

मम नाम धवलः (Mama Naama Dhavalah)
धवलः मम नाम (Dhavalah Mama Naama)
धवलः नाम मम (Dhavalah Naama Mama)
नाम मम धवलः (Naama Mama Dhavalah)

In other languages, the order of the words will change the meaning of the sentence, thus violating its integrity. Here, neither the meaning of the sentence changes, nor using the sentence changes the meaning of the context. For those computer folks amongst us, I’d say that I’m reminded of Referential Transparency that we deal in programming. In Object-oriented computer languages, we have value objects that are referentially transparent, in functional programming languages, we say that a pure function (slides 2-10) is referentially transparent. In Computer Programming, Referential Transparency is with reference to Time (which implies order), whereas in Sanskrit, it is from the perspective of Order of words. So, Sanskrit is immensely flexible while arranging the words to construct a sentence without changing its meaning. However that does not mean that there is no order at all. There are places where order needs in a sentence to be respected, else it can alter its meaning.

In English language, the famous statement made by Napoleon – “Able was I ere I saw Elba”. Phonetically, whether you utter the sentence from left to right or from right to left, the sentence sounds the same and also the meaning of the sentence is not altered. This is called as a Palindrome. In Sanskrit, such a thing is called विलोम (Viloma). Viloma means reverse. In Sanskrit, you don’t just have sentences but can have ‘palindromic’ poems as well. You can check – Ramakrishna Vilomkavyam. In this if you read it from Left to Right, it is for Lord Rama and if you read it from Right to Left, it relates to Lord Krishna. There many Vilom Kavyas (विलोम काव्य) काव्य means poetry. In fact, in Sanskrit, there is Spatial Palindrome, check this post out.

Now lets look at other creative uses of this language in the past. If you are aware of the Shurpankha story from Ramayana, especially the part of the story wherein her nose was cut by Lakshmana. She goes back to Ravana and conveys what all happened to her. The poet was faced with the challenge to create a verse that would physically mimic her voice quality to bring out the expression of her pain and without the nose. The poet did not use any nasal or oro-nasal sounds for the creation of the verse. Pure nasal sound (sound produced from the nasal cavity) in Sanskrit is Anusvara whereas Oro-Nasals sound (sounds produced from oral and nasal cavity) are – ङ (ṅa), ञ (ña), ण (ṇa), न (na), म (ma).

Yet another example can be found is that of Niroshthya Ramayana. The creator of this observed that when a few people pronounced labial sounds: Pa – प, Pha – फ, Ba – ब, Bha – भ, Ma – म. While reciting Ramayana, they would spray saliva all over and this to the creator was disrespectful. So, the person ended up creating a version of Ramayana where the use of all labial sounds was restricted. This resulted in Ramayana, without the word राम – Rama.

Session 2: Sambhasanam (Listening and Speaking Sanskrit)
Initially, when Sanskrit existed, it was not even called Sanskrit, instead it was called भाषा (Bhasha). The Root sound of भाषा is भाष् (Bhash), which means to speak, later on it acquired the name Sanskrit. Also, Sanskrit is actually called संस्कृतम् (Sanskritam). The root sound is सम् (Sam), which means totality, sum, completeness, togetherness, integrity, perfectness and कृतम् (Kritam) means sculpted or created. So, संस्कृतम् (Sanskritam) essentially means sculpted to perfection.

When learning any language, the first step is संभाषणम् (Sambhasanam), which basically listening first – श्रवणम् and then speaking – वदनम्. First, we got introduced to 2 words मम and तव

  1. मम (Mama) means mine or belongs to me.
  2. तव (Tava) means thine or belongs to you.

Dr. Sampadanandaji then gave examples of verbless sentences, and yes its possible to construct verbless sentences in Sanskrit, not in English. He also said that through out the 7 days we will only use singular and not plural for things. Here are the examples using it with body parts –

  1. मम शरीरम् (Mama Shariiram) means my body.
  2. मम मुखम् (Mama Mukham) means my face.
  3. मम मुण्डम् (Mama Mundam) means my head.
  4. मम नासिका (Mama Nasikaa) means my nose.
  5. मम ग्रीवा (Mama Grivaa) means my neck.
  6. मम वक्षः (Mama Vakshah) means my chest.
  7. मम ऊदरम् (Mama Udaaram) means my stomach.
  8. मम पादः (Mama Paadah) means my leg.

In the above, Neuter Gender ends with अम् (Am) as in शरीरम्, मुखम्, मुण्डम्, ऊदरम्; Feminine Gender ends with आ (Aa) as in नासिका, ग्रीवा; and Masculine Gender ends with अः (Ah) as in पादः. The word वक्षः (Vakshah) is a ‘s’ ending word in neuter gender. During this session we were asked to construct on our own other verbless sentences and speak it out loud to the class. We also learned what the 5 fingers are called in Sanskrit.

  • कनिष्ठिका (Kanishtika) means Pinky finger.
  • अनामिका (Anamika) means Anonymous finger.
  • मध्यमा (Madhyama) means the Middle finger.
  • तर्जनि (Tarjani) means the First finger and comes from the word तर्जन (Tarjan) which means to threaten.
  • अङ्गुष्ठ (Angushtha) means Thumb.

Then further, a verb was added. We learnt the verb – अस्ति (Asti) and नास्ति (Nasti) – means it is about presence and absence respectively. Example usage in sentence would be

  1. मम पिता अस्ति (Mama Pitaa Asti) means my father is present.
  2. मम माता नास्ति (Mama Mataa Naasti) means my mother is absent.

नास्ति means Not Present, that is absent. नास्ति = न + अस्ति (Naasti = Na + Asti). In English न would translate to No). न is negation in Sanskrit. Use of नो (No) is also perfectly valid in Sanskrit.

We then were asked to formulate questions and the next person would answer the question. An example question is – किं तव पिता अस्ति (Kim Tava Pita Asti?) means – Is your father present?

Lets take yet another question – किं तव नाम धवलः (Kim tava naama Dhavalah?). In English it would translate to – Is your name, Dhaval? In response to a question having binary answer, one can respond either with affirmation or a negation.

  1. An affirmative answer – आम् मम नाम धवलः (Aam, Mama naama Dhavalah) means Yes, My name is Dhaval.
  2. If you are not Dhaval, negative answers could be
    1. मम नाम धवलः नास्ति (Mama naama Dhavalah naasti) means my name is not Dhaval.
    2. न मम नाम सम्पद् (Na Mama naama Sampad) means No, my name is Sampad.

When asking a question here the order needs to be maintained, else its inappropriate and can mean something else.

We completed the session and Dr. Sampadanandaji had a beautiful way of saying good-bye. He said that, today we use many words – Good bye, See you, God bless you, Catch you later etc… and we say that very casually and don’t probably mean it. The Mother was asked this question – What should be our attitude when we depart from each other? What should we say? The Mother said – Be quiet and say – May the Divine Presence be with you. In one of her messages she has said that at every step the unforeseen and the unknown is before us and only the Divine can protect. The verse that we learnt has that sense in it and then led the entire class by rendering the beautiful composition done at Sri Aurobindo Ashram dedicated to The Mother –

पुनर्दर्शनाय पुनर्हर्षणाय
पुनर्मातृदेव्याः कृपावर्षणाय

It means- We depart from each other to see each other again, rejoicing together again, and for receiving the shower of the Mother’s Grace again. पुनर्दर्शनाय (Punardarshanaya) means to see each other again, पुनर्हर्षणाय (Punarharshanaya) means to rejoice again, पुनर्मातृदेव्याः (Punarmatrudevyah) means from The Mother again, कृपावर्षणाय (Kripavarshanaya) means to receive the shower of Grace.

Well, that’s all for now. If you enjoyed this, check out the post for Second half of this day – Wonders of Sanskrit Alphabets.

Science Of Living Workshop @ Sri Aurobindo Society – A Synopsis


Last Christmas Vacation and into the New Year 2016, my family was at the Sri Aurobindo Society, Pondicherry attending the Science of Living Workshop. It was quite a good experience for all of us for 3 days with lots of activities and the learnings that ensued those activities. I am jotting it down here chronologically day-by-day.

1) Introductions
The workshop started by asking all the participants to introduce themselves and to identify any two from the many flowers arranged, they also need to tell why they like that particular flower. For example, I chose 2 flowers – the flower of Indian Cork Tree (Tree jasmine or Millingtonia hortensis) and Garden gladiolus (Gladiolus Xhortulanus), both of them white (personally because I like white color) and for me it is very soothing, an embodiment of peace and harmony. The facilitators then explained the spiritual significance of the flowers given by The Mother to each of the flowers chosen.

For example, my wife chose – Marigold flower and the spiritual significance given by The Mother is – Plasticity

2) Life and Self
After the introductions, each participant was given a set of questions. In essence, it was about reflecting on oneself and then answering the questions therein (only to be reviewed again by oneself). The idea is to use this tool for personal retrospective.

3) Well-Being and Being Well
This session started with deconstruction of the word – Psychosomatic – ‘psycho’ means ‘relating to mind’ and somatic means ‘relating to body’ and so psychosomatic diseases are those which have their birth place in the mind, and subsequently travel outward and enter the body. The important message was that the body manifests the thoughts and emotions, either positive or negative, so we need to careful about the quality of thoughts and emotions that we generate in our interactions with our own self and others. The four dimensions of Well-being in an individual are the Physical well-being, Vital (emotional) well-being, Mental well-being and Spiritual well-being. Physical well-being can be achieved through daily exercises; Vital or emotional well-being can be attained by doing work or choosing an occupation that is in harmony with individual nature, temperament and capacities; Mental well-being can be established by having peace and tranquility in mind, and eventually spiritual well-being by awakening to the inmost self. To establish all these one quality that is required is Perseverance. What is Perseverance? When patience becomes dynamic, it is called as Perseverance, in other words – Perseverance is dynamic Patience.

We were then presented a case study on how one can use consciousness as medicine – “Love healed the bones” which appeared in the Namah magazine (Vol. 22, Issue 1, 24th April 2014).

4) Demystifying Life Aspects
In essence, each human being is a triple body – physical, vital and mental bodies (Annamayakosha, Pranmayakosha and Manomayakosha) and soul the inhabitant works through this triple body. It is very necessary to make sure that each of these bodies are harmonised for the well-being of an individual.

5) Playing Together
In the post lunch session on Playing Together, all the parents along with the children played together by doing Origami. We all learnt from the facilitators how to create beautiful butterflies out of plain paper and later we all were given special Origami paper, which we all coloured it using crayons and then folded them to make colourful butterflies. The core learning here was about improving one’s grasping, developing concentration, and above all understanding symmetry and perfection involved in folding the paper to create beautiful butterflies.

6) Collective Chanting
This was a nice experience of everyone in the workshop chanting together the invocatory mantra of Isha Upanishad (The starting Om needs to be recited such that a time split of 60-40 is maintained for O-m).

ॐ पूर्णमदः पूर्णमिदं पूर्णात्पुर्णमुदच्यते
पूर्णश्य पूर्णमादाय पूर्णमेवावशिष्यते ॥
ॐ शान्तिः शान्तिः शान्तिः ॥

As a collective the chanting was very powerful and could feel the pulsations within me.

Day 2:
1) The ‘others’ in Life
This session started with a ‘game of moving chairs’ wherein each couple would take turns at this game. For each couple round (time-boxed to 15 mins), there were bunch of chairs arranged and one of the persons in the pair was blind-folded, with the second person giving verbal instructions for the first to move from one end of the room to the other end step-by-step. Upon reaching the destination, touch a pre-designated target. During the game, one can hear the couple’s argue and talk to each other. Also, the chairs were not kept static, they were moved by the facilitators to simulate changing nature of life. The essence of the game was to convey the message –

  • Putting in one-self in the shoes of the other.
  • Trusting the other person.

2) Creativity Bonds
In the second half, all the children along with the parents played various games.

Water Cups

Moving with a glass full of water (up to its brim) from one end to the other end of the room without spilling it.

Going over the steps by balancing the squares on the stick and ensuring that the squares do not fall anywhere during the journey.

These games don’t require a huge set-up, but can go a long way in developing –

  • Body consciousness
  • Concentration
  • Patience

3) Movie: Mr. Magorium’s Wonder Emporium
All the children with parents watched this wonderful movie. There are lot of learnings that one can derive from this movie.

  • Non-attachment to possessions
  • Believing in oneself
  • Living life with Exuberance
  • Being open to change

If you have not seen the movie, I would highly recommend it.

Day 3: Trip to Sharanam
On the last day, we were taken to Sharanam, about 11Kms from The Society Office. The space is wonderfully done, all using bricks that are handmade and not dried in fire, they are left to dry naturally in the air. Cement and concrete is not used to build this structure.


1) Interconnectedness
In this session, all the participants were asked to create something jointly (all families together) with something that conveyed the spirit of this word.


2) Tools for Life Beautiful
In this session, we were acquainted with tools for making life beautiful. Jotting them here for reference.

  • Gratitude
  • Aspiration
  • Stepping Back
    • Guided by Larger Purpose
    • Step Inside before you Step Outside
  • Beauty and Harmony

Now, all these are tools are good, but how do we use them on a daily basis so that it is not mere mental gymnastics. As in everything its the implementation that is difficult, not the understanding. Of all the above tools, generally speaking, The Mother has said that begin with Beauty and Harmony in the physical as its near to us and then gradually work your way inwards. Trying to establish beauty and harmony in our immediate physical surroundings – cleanliness at home, at workplace etc… Beauty and harmony while doing our daily chores, harmony in our interactions with others, for example – as a professional, if you are a software developer, ask yourself – how can I make this code beautiful or write beautiful code?

3) Surprise video’s of children
As parents, we were asked to fill in a questionnaire (both the mother and father fill answer separately and merge their answers) pertaining to our children. While parents were attending the sessions, children were playing amongst themselves and under the supervision of Sri Aurobindo Society’s facilitators. They also asked them questions about parents and video-shooted their responses (as parents we were not told about this). Later both, the parent to child and child to parent feedback was shared in a congenial setting. Sharing Parent-Children 360 degree feedback in such a manner was the best part of the entire workshop. I learnt that this is a powerfully simple tool to see each other’s perspectives.

I have skipped a couple of sessions as I don’t completely recall what we did in them, but that does not matter, the above conveys the spirit of the 3-day program very nicely.

Game of Life in RxJS (and ReactJS) and RxGroovy


, ,

Last week at the Global Day of CodeRetreat in Mumbai, I wrote the Game Of Life using RxJS. Though I used the Node.js and text console to render the game during the retreat, below is the HTML version for rendering an Oscillating Pulsar. Hit Run to see it oscillate.

Code uses all pure functions and ES6 arrows. Below is the excerpt, Check out the code on GitHub if it interests you.

var cellAt = function(r, c, world) {
  var row = world[r];
  if (row == undefined || row[c] == undefined) {
    return 0;
  return world[r][c];

var neighbours = function(r, c, world) {
  return [
    cellAt(r-1, c-1, world), cellAt(r-1, c  , world), cellAt(r-1, c+1, world), 
    cellAt(r,   c-1, world),                          cellAt(r,   c+1, world), 
    cellAt(r+1, c-1, world), cellAt(r+1, c  , world), cellAt(r+1, c+1, world)  

var isAlive = cell => cell != 0;
var isUnderPopulated = liveNeighbours => liveNeighbours < 2;
var canSurvive = liveNeighbours => liveNeighbours == 2 || liveNeighbours == 3;
var isOverCrowded = liveNeighbours => liveNeighbours > 3;
var canReproduce = liveNeighbours => liveNeighbours == 3;

var newCell = function(cell, neighbours) {
  var liveNeighbours = neighbours.reduce((a, b) => a + b);
  if (isAlive(cell) && (isUnderPopulated(liveNeighbours) || isOverCrowded(liveNeighbours))) {
      return 0;
  if (isAlive(cell) && canSurvive(liveNeighbours)) {
      return 1;
  if(!isAlive(cell) && canReproduce(liveNeighbours)) {
      return 1;
  return 0;

var newWorld = 
  oldWorld =>, r) =>, c) => 
      newCell(oldCell, neighbours(r, c, oldWorld))));

and here is the HTML. In the inline script below, I use Rx.Observable‘s generateWithRelativeTime to produce a new world from seed world. It starts with the seed world pattern and ticks every 1 sec producing a new world from the previous world based on the rules of the game encoded above. The subscribe function’s success callback uses the render function display the newly generated world by mapping the 2D world-array to HTML divs. I take only first 30 generations as this pattern continues infinitely.

<!DOCTYPE html>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/gameOfLife.css">
    <title>Rx Game Of Life</title>
    <div id="output"></div>
    <script src="lib/rx/rx.all.js"></script>
    <script src="src/gameOfLife.js"></script>
    <script src="src/gameOfLifePatterns.js"></script>
    function toDiv(cell) {
      var cellStyle = (cell == 0) ? "dead" : "live";
      return "<div class='cell cell-" + cellStyle + "'>&nbsp;</div>";
    function render(world)  {
      var html = =>
                    .replace(/,/g, "");
      document.getElementById("output").innerHTML = html;
    var seedWorld = oscillatingPulsar();

      w => true, // don't terminate
      newWorld,  // next function
      w => w,    // return value
      () => 1000 // tick every
      e  =>,
      () =>"*** Complete ***")

You can replace line 30 with calls to other patterns to see them in action.

Below is the game using ReactJS. As ReactJS helps render the View in MVC, only view related functions: toDiv and render have changed to accommodate it. Additionally, I’ve passed row and column ids as rid and cid respectively, so that ReactJS does not give a warning:

Warning: Each child in an array or iterator should have a unique "key" prop. Check the React.render call using <div>.

<!DOCTYPE html>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/gameOfLife.css">
    <title>Rx Game Of Life Using ReactJS</title>
  <div id="output"></div>

  <script src="lib/rx/rx.all.js"></script>
  <script src="lib/reactjs/JSXTransformer.js"></script>
  <script src="lib/reactjs/react.js"></script>
  <script src="src/gameOfLife.js"></script>
  <script src="src/gameOfLifePatterns.js"></script>

  <script type="text/jsx">
    function toDiv(cell, rid, cid) {
      var cellStyle = (cell == 0) ? "dead" : "live";
      return (<div key={rid + "" + cid} className={`cell cell-${cellStyle}`}>&nbsp;</div>);

    function render(world)  {
      var grid =, rid) => {
        return (<div key={rid}>
                  {, cid) =>
                     toDiv(cell, rid, cid)
    var seedWorld = oscillatingPulsar();

      w => true, // don't terminate
      newWorld,  // next function
      w => w,    // return value
      () => 1000 // tick every
      e  =>,
      () =>"*** Complete ***")

See it in action below 🙂

Below is the game using RxGroovy.

import rx.Observable
import java.util.concurrent.*

List.metaClass.collectWithIndex = { body ->
  def idx = 0
  delegate.collect { body(it, idx++) }

def cellAt(rowIdx, colIdx, world) {
  def r = rowIdx >= 0 ? rowIdx : Integer.MAX_VALUE
  def c =  colIdx >= 0 ? colIdx : Integer.MAX_VALUE

  def row = world[r]
  if (row == null || row[c] == null)
        return 0
  return world[r][c]

def neighbours(r, c, world) {
    cellAt(r-1, c-1, world), cellAt(r-1, c  , world), cellAt(r-1, c+1, world),
    cellAt(r,   c-1, world),                          cellAt(r,   c+1, world),
    cellAt(r+1, c-1, world), cellAt(r+1, c  , world), cellAt(r+1, c+1, world)

def isAlive(cell) { cell != 0 }
def isUnderPopulated(liveNeighbours) { liveNeighbours < 2 }
def canSurvive(liveNeighbours) { liveNeighbours == 2 || liveNeighbours == 3 }
def isOverCrowded(liveNeighbours) { liveNeighbours > 3 }
def canReproduce(liveNeighbours) { liveNeighbours == 3 }

def newCell(cell, neighbours) {
  def liveNeighbours = neighbours.inject(0) {a,e -> a + e}
  if (isAlive(cell) && (isUnderPopulated(liveNeighbours) || isOverCrowded(liveNeighbours)))
    return 0

  if (isAlive(cell) && canSurvive(liveNeighbours))
    return 1

  if (!isAlive(cell) && canReproduce(liveNeighbours))
    return 1

  return 0

def newWorld = { oldWorld ->
  oldWorld.collectWithIndex { row, rIdx ->
    row.collectWithIndex { oldCell, cIdx ->
      newCell(oldCell, neighbours(rIdx, cIdx, oldWorld))

def blinker = [
  [0, 1, 0],
  [0, 1, 0],
  [0, 1, 0]

Observable.interval(1, TimeUnit.SECONDS)
.scan(blinker, { old, tick -> newWorld(old)})
.take(10) // 10 generations
.subscribe (
    { println("$it") },
    { e -> println("onError() => $e") },
    { println('onComplete() => *** Complete ***') }

Equals, HashCode and ToString Builder using λ’s in Java8

Based on my earlier post on this in C#, I thought it would be nice to translate it to Java8. So here are end up with the implementation in Java8, using lambdas. If you have a Money value object, here is how you would want to use the EqualsHashCodeToStringBuilder in Java8.

public class Money {
  public final String currency;
  public final double amount;
  private final EqualsHashCodeToStringBuilder<Money> builder;

  Money(String currency, double amount) {
    this.currency = currency;
    this.amount = amount;
    this.builder = new EqualsHashCodeToStringBuilder<>(this)
            .with(m -> m.currency)
            .with(m -> m.amount);

  public String toString() {
    return builder.toString();

  public boolean equals(Object that) {
    return builder.equals(that);

  public int hashCode() {
    return builder.hashCode();

Here is the code for EqualsHashCodeToStringBuilder. You can download the code base from

public class EqualsHashCodeToStringBuilder<T> {
  private final T left;
  private final String className;
  private List<Function> properties = new ArrayList<>();

  public EqualsHashCodeToStringBuilder(T left) {
    requireNonNull(left, "Left operand must be supplied");
    this.left = left;
    this.className = left.getClass().getSimpleName();

  public <U> EqualsHashCodeToStringBuilder<T> with(Function<T, U> property) {
    requireNonNull(property, String.format("Please specify %s's property", className));
    return this;

  private <U> boolean isEqual(U leftValue, U rightValue) {
    if (areNull(leftValue, rightValue)) {
      return true;
    if (isNull(leftValue) && nonNull(rightValue)) {
      return false;
    return leftValue.equals(rightValue);

  private <U> boolean areNull(U leftValue, U rightValue) {
    return isNull(leftValue) && isNull(rightValue);

  public boolean equals(Object other) {
    if (isNull(other)) {
      return false;
    if (left == other) {
      return true;
    if (left.getClass() != other.getClass()) {
      return false;
    T right = (T) other;

      .map(property -> isEqual(property.apply(left), property.apply(right)))
      .allMatch(x -> x == true);

  public int hashCode() {
      .map(property -> {
        final Object value = property.apply(left);
        return isNull(value) ? 0 : value.hashCode();
      .reduce(1, (hashCode, value) -> 31 * hashCode + value);

  public String toString() {
      .map(property -> {
         final Object value = property.apply(left);
         return isNull(value) ? "null" : value.toString();
      .collect(joining(", ", String.format("%s(", className), ")"));