Showing posts with label panini. Show all posts
Showing posts with label panini. Show all posts

Monday, November 19, 2012

The linguistic creamed milk

There are sweets and there are sweets. It is the envy of every NRI, whose friend returns from India after attending sumptuous weddings or festivities, and enumerates the different sweets that were devoured. How many different milk-based sweets and flavors! So much so that, the states are known based on the milk-sweet based identity - whether it is doodh-peda from gujarat or rasagolla from bengal or a simple paayasam from the south.

Amongst all, I would say the poor-man's-king-of-sweet is the "thiratti-paal", literally "condensed milk". Usually it is called "khoa", but the process of preparing them are different. Probably every Indian mom has made this at home. With just 2 to 3 ingredients (milk, curd and sugar or ghee), but a relatively elaborate process of making it, thiratti-paal was sometimes more sought after in our family, matched only by Venky's laddu. Even though all it requires is just to boil the milk and carefully adding curd, getting the right amount of sweetness is an art form. Hasty adding of the curd or letting the cream stick to the bottom of the vessel can quickly spoil the taste. And the best sweets are those that can be savored for a long time without feeling the excessiveness of sugar.
image credit www.mammoos.com

Human mind is remarkably capable of remembering information in summaries and at the same time processing and expounding a piece of information into elaborate details. Honestly speaking, we really do not know how the mind does it. Many of you may remember such exercises from your high school literature classes: analyze and write a detailed essay on the character of Macbeth OR write a short summary of what you learnt from the "crow took the vada from the daadi-ma" story.

The fact that mind can zip information to remember and also unzip information by "filling-in" the gaps, is by itself quite a remarkable talent. No better it is seen than in children, especially toddlers, when they light up to summarize what they learnt, capturing the most interesting and vocal sound-bits. What you also notice is that the larger the information, the less-juicy details tend to quickly get lost and only the meaty and essential stuff reflect in the brains.

Lets take an example: If I mention the words - crow, vada and fox, you can pretty much make up a whole story based on that. Obviously you know the story already, but even if you dont, you can make up a story based on related information that you already know. Another example: "West side story". You might not immediately know the story, but if I just throw in the words "like Romeo and Juliet", a story unfolds in your mind pretty much immediately.

So how small can the information be, in order to not lose its purpose, yet be meaningful enough to expound ?

This was the question that likely tormented our ancient rishis, who were at ease versifying the known and the unknown into musical chandas. Thus came into existence - the "sutram" format that carried the smallest possible information, without losing its context and meaning. It is one of the most remarkable linguistic inventions ever to assist humans remember and retain information with the highest fidelity, that has shaped hinduism and the culture of India. This format has been thoroughly analyzed, distilled, nurtured and turned into an art form by its exponents. It is like several gallons of milk boiled to a handful of cream, carefully adding words only when its imperative. Just like the thiratti-paal, condensing the material unto itself, to extract the sweetness out of it.

For some reason, we are suckers for who those end up in the top. Top 5 songs of the week, top 10 beaches, top 10 smartphones, top 10 poisonous animals, top 20 most powerful people - the list of "tops" are endlessly written and forgotten. Even Samskrita Literature is not spared of this - we do have a "Top 5" in the Sanskrit literature - the pancha-mahA-kAvya: abhijnaana-sakuntalam, raghu-vamsa, kiraataarjuniyam, naishadhiya-caritam and shishupala-vadham. Well, it has been in top 5 for the last 1500 years.

But why stop with just the kavya-literature? I'm partially pained that no one has come up with the "Top 5 sutrams". But whats stopping us, lets come up with our own list!

#5: इको यण् अचि | iko yaN aci | 

This sutram is in our 5th place in the list for two reasons: a) the amount of specific information conveyed in about 5 syllables is equivalent to creating an 8x13 sandhi matrix b) the sutram consists entirely of pratyAhAra-s - which in turn is an encoding of about 25 aksharas.

Panini has come up with several such sutrams, but due to the massive popularity amongst vayyakaraNa-s for quoting this sutram at the drop of the hat, this is our 5th best sutram of the .. err.. last three thousand years.

#4: वृद्धिरादैच् | vriddhiraadaic | 

Yet another gem from Panini, who attempts a technical sutram and managala-sutram at the same time, keeping his promise to be as short as possible. vriddhiH-aat-aic, though technically defining the word "vriddhiH" to be equivalent to aa, ai and au, also conveys that "let there be a vriddhi of this work".

A rare clever pun on both technical and business purposes at the same time, Panini's first sutram of aShTAdhyAyI gets our 4th best.

#3: अथातो ब्रह्म जिज्ञासा | athāto brahma jijñāsā | 

Coming in at number 3, is "the time to enquire about truth". So starts bAdarAyaNa vyAsa in his weaving of formidably cryptic brahma-sutram. The sutrams that have at least given rise to three widely different "matha-s" - from "all is brahman" to "jiva and brahman are fundamentally different", it occupies the foremost place in the "prasthAna-trayI" triplet of intellectual expositions. Similar to the technology world, where no one is an architect unless he/she has a few white papers to his/her credit, no one is a philosopher unless he has written a bhAShyam on brahma-sutram, upanishad-s and bhagavad-gita. The brahma-sutram has fundamentally shaped the philosophy of the Hindus in a very subtle, yet deep way.

#2: योगश्चित्त वृत्ति निरोध: | yogashchitta-vritti-nirodhaH | 

The West have taken over Yoga. Or so it seems. Though yoga is not "owned" by the East, there is a disconcerting wave of misinterpretation about yoga. Fancily-named or self-named yoga techniques have flooded the markets in the last few decades. In the United States alone, yoga is conservatively estimated to be a $6 billion dollar industry. The only ever prop I ever had, when I learnt yoga in India, was an old blanket. Compared to the props available in the modern market, it is very clear that yoga has been stretched for its popularity. I wonder why no one has yet come up with the pricing model of "pay-per-pranayama" - you know, just like the cloud-based models, where you pay per GB or CPU cycle. I'm sure the pricing models like "25 prANAyAma-s per dollar", "two free breath-ins for every breath-out" or "early bird sign ups will get an extra arm twist" will be a run-away hit.

So much ignorance is perpetuated that the original definition of yoga is completely sidelined. Yoga is translated into "union", which is probably the farthest explanation from being anything meaningful.

For giving a mind-blowingly precise definition of yoga, which is the exact opposite of yoga-marketing, namely "Yoga is the cessation of mind-activity" - the patanjali's yoga-sutram occupies the second best sutram in our list. Patanjali has given precise definitions of several other psychological terms, which the modern academia is quietly accumulating into their own curriculum, but we will take his first as the best.

#1: धर्मार्थकामेभ्यो नमः | dharma-artha-kamebhyo namaH | 

Our top most sutram is not from diwali-sounding grammar rules or nuclear-fission like brahma-sutram. It is from a sage who condensed the human feelings of love into sutram format - by far the most innovative application of sutrams and challenging the traditions of his times. No kick-off mangala-sutram or slokam for this guy, and yet he dares to miss a leg of one of the "four pillars" of sanAtana dharma. He could have included the word "mokSha" in his sutram, no one would have cared, but his work is about human emotions and mokSha does not have a definite place.

For being practical, realistic, brazenly bold, innovative and perhaps a path-breaker of his times, Vatsyayana's sutram is the top most in our list of sutrams of the last 3 millenia.

Things may change soon in the next 3000 years, keep watching this space, and until then, dhanyavaadaH !

Sunday, December 11, 2011

sthAne antaratamaH

A Functional Approach

It is very interesting to observe that Panini's approach to sandhi-s is thoroughly function oriented and very algebraic in execution. Sandhi-s in Samskritam are profound sophistications. We shall see how functional programming naturally fits into Panini's approach. Once again I'm not describing theories, but real testable executable code and assertable outputs.

For the samskritam-dsl project, I was trying to come up with a simplistic representation of sandhi-s. The famous iko yan aci sandhi belongs to the purva rupa sandhi (the first word gets modified) and Panini's general technique can be functionally written as:

f = sandhi(sthana, adesha, vidhi, purva, para)

This is understood as:  "The adesha (substitute) replaces the sthana (substituted) of the purva shabda when vidhi is true on the para shabda"

Panini uses natural linguistic approach and places sthana in 6th vibhakti, adesha in 1st vibhakti and vidhi in 7th vibhakti.

So lets rewrite this in functional programming notation -

  //purva rupa sandhi sutra - closure
  def purvaRupaSandhi = {sthana, adesha, condition, words ->
    def (purva, para) = words.tokenize()
    if (condition(para)) {
      def k = sthana.substitute(adesha, purva.lastVarna())
      purva.replaceLast(k)
      purva + para
    } else {
      words
    }
  }

Here sthana is the list of substituted varnas (eg ik), adesha is the substitute varna (yaN). Condition is not a list but something that evaluates to true or false based on the para shabda. So its a closure again.

  def aci = { word -> word.varnas()[0].svara() }
  def jshi = { word -> word.varnas()[0] in sivaSutra.jsh }
  

Basically the above closure evaluates to true if the first varna of the shabda is a svara.

Remember we defined the purvaRupaSandhi as a completely generic closure. It will take any sthana, adesha and condition. How do we apply this to iko yaN aci or say, jhalaam jash jhashi?

Groovy provides the "currying" feature --

  def iko_yaN_aci = purvaRupaSandhi.curry(sivaSutra.ik, sivaSutra.yN, aci)
  def JalAm_jash_Jashi = purvaRupaSandhi.curry(sivaSutra.Jl, sivaSutra.js, jshi)

Real functional programming stuff here. aci and jshi are closures/functions which are passed to purvaRupaSandhiwhich evaluates it based on the para shabda.

Now for some more beauty. How do we substitute sthana with adesha? Panini defines a really brilliant sutra 'sthAne antaratamaH' - the closest phoneme of the adesha to the sthana, must substitute the sthana. Now how do we find the closest ? When pronouncing it is easy to realize that i is close to y or u is close to v. But how does that translate to programming terms? This is when it dawns upon us that Panini's approach is extremely methodical.

Recall the definitions of phoneme-sets?

akUhavisarjaniyanaam kanTaH | icuyashaanaam taalu | RturaShaaNaam mUrhda | Ltulasaanaam danta | upUpadhmaanIyaanaam oshta |

So if a varna from sthAna exists in one of the above sets of phonemes, then the common varna between that phoneme-set and the adesha will substitute the sthana !!!

Illustration: jhalaam_jas_jashi

example: ap + dhi

purva shabda - ap (varna is p), para shabda - dhi, satisifies condition jashi (dha). Good.

sthAna - p, adesha will be one of jash = [j, b, g, d, dh] -- now which to pick?

p exists in oshta phoneme-set; so we have to pick one from pu = [p, ph, b, bh, m] - but which one?

Remember jash adesha is [j, b, g, d, dh]. So intersect oshta with adesha, which will result in b -> that substitutes 'p' - resulting in abdhi !

Can you now appreciate the functional beauty of maheshvara sutra?

So the formula is
  
  def ku = [k, kh, g, gh, ~n]
  def kanta = ['a', 'A'] + ku + ['h'] + [':']
    Closure sthaneAntaratamaH = { x, adesha ->
    for (def phonemeSet : [kanta, taalu, murdha, danta, oshta, dantoshtam]) {
      if (x in phonemeSet) return phonemeSet.intersect(adesha)
    }
  }
 }

That's it!! The 2 closures basically take care of any purva rupa sandhi rule! Only the additional conditional closures (aci, jashi etc.) must be provided as required.

Finally we verify

assert iko_yan_aci("iti api") == "ityapi"
assert jhalaam_jash_jashi("ap dhi") == "abdhi"

As usual the code can be found at github.com/vasya10/samskritam.

PS: Post this blog, I tried to verify purvaRupaSandhi closure by adding another rule "stoH shcuna shcu:" and it worked just fine. But there is a catch. The shcuna in the rule is not in 7th vibhakti, but is in instrumental case. And there is a reason why Panini uses 3rd vibhakti. The 7th vibhakti indicates the rule to be applied with respect to what follows, while the 3rd vibhakti implies just the contact of two varna-s are sufficient to produce the sandhi. The closure does not take care of that yet.

The functional programming approach of Panini makes me believe that universities should include ashTAdhyAyI as a course in Computer Science, instead of just being a research subject to elite academicians.

Thursday, November 17, 2011

The Chapter 8 DSL

Domain Specific Language is fast becoming a popular way to describe a problem or a solution for a specific domain. The quality and readability of code using DSL is magnitudes above the regular "technical" code (using Java/C# for eg). Since information about DSL can be googled amply, I am not going to spend time writing on what a DSL is.

In many of the previous posts, I had used pseudo-code, demonstrating parallels in programming to Panini's techniques. Time to call the bluff now. Presented below is a seriously tested code. Here is a DSL that closely models some basic techniques of ashtaadhyaayI, specifically the maheshvara-sutra-s and those darning "it" rules. I'm using Groovy for the implementation, as I feel that it's syntax is more natural to read than that of Scala or Ruby.

Let's define some classes.

[Listing 1: SivaSutra.groovy]
package ch8

import java.util.List

/**
 * Implementation of Maheshvara Sutra using SimpleScript transliteration scheme
 * The table itself can be moved to a groovy configuration file to allow a different scheme like HK, ITRANS or AST
 * 
 * @author vsrinivasan
 */
@Singleton
class SivaSutra  {

  //siva-sutraani
  List table =
  [
    ['a', 'e', 'u', 'N'],
    ['r.', 'l.', 'k'],
    ['E.', 'o', 'n'],
    ['i', 'O.', 'c'],
    ['h', 'y', 'v', 'r', 't'],
    ['l', 'N'],
    ['n.', 'm', 'n', 'N', 'N.', 'm'],
    ['J', 'B', 'n.'],
    ['G', 'D', 'D.', 's.'],
    ['j', 'b', 'g', 'd', 'd.', 's'],
    ['K', 'P', 'C', 'T', 'T.', 'c', 't', 't.', 'v'],
    ['k', 'p', 'y'],
    ['s', 's.', 'S', 'r'],
    ['h', 'l']
  ]

  List list = table.flatten()

  int indexOf(String varna) { list.indexOf(varna) }

  @Override
  Iterator iterator() { list.iterator() }

  //eShaam antyaaH it
  List itMarkers = table.collect { it.last() }

  /**
   * is this iT-marker?
   * this finds only 'pratyahara iT' is defined, for other it-s see ItRules.groovy
   * 
   * @see ItRules
   */
  boolean isIt(f) { itMarkers.contains(f) }

  /**
   * expands a given pratyahara, including all the iT-s
   * not for practical purposes, but good for testing
   * 
   * @param pratyahara
   * @return
   */
  List expand(String pratyahara) {
    def (begin, end) = pratyahara.varnas()
    list[begin..end]
  }

  /**
   * returns the real pratyahara varna-s, excluding the intermediate it-markers
   * very procedural implementation, need to make it groovy-like
   * 
   * @param pratyahara
   * @return
   */
  List collect(String pratyahara) {
    def (begin, end) = pratyahara.varnas()
    boolean start = false
    def result = []

    table.each { line ->
      line.each { item ->
        if (item == begin || start) {
          if (item != line.last()) {
            result << item
            start = true
          }
          if (item == end && item == line.last()) {
            start = false
          }
        }
      }
    }
    return result
  }
}


[Listing 2: ItRules.groovy]
package ch8

@Singleton
class ItRules {

  //#(1.3.2) upadeshe ajanunaasika iT, anunAsika-s are denoted by a "-" at the end,
  //  may be M would be a better option?
  def ajanunasika = 'aAeEuUr.R.l.E.IOO.'.varnas().collect { it + "-" }

  //cutU
  def cu = 'cCjJn.'.varnas()
  def tu = 'tTdDN'.varnas()

  //s.asca, denoting as "sha" for convenience
  def sha = ['s.']

  //lasaku (ataddhite)
  def ku = 'kKgGn'.varnas()
  def lasaku = 'ls'.varnas() + ku

  //some more to be defined

  //#(1.3.3) halantyam - check if the last char is hal
  SivaSutra sivaSutra = SivaSutra.instance
  boolean hasHalantyam(String pratyaya) { pratyaya.varnas().last() in sivaSutra.hl }

  //allItMarkers except hal, which is applicable only to last letter
  def allItMarkers = ajanunasika + cu + tu + lashaku

  boolean isAnunasika(String varna) { varna.endsWith('-') }

  boolean isItMarker(String varna) { varna in allItMarkers }

  String tasyaLopah(String pratyaya) { (pratyaya.halantyam().varnas() - allItMarkers).join() }
}

[Listing 3: Main.groovy]
package ch8.tests

import java.util.List

import ch8.ItRules
import ch8.SivaSutra
import ch8.schemes.SimpleScriptScheme
import ch8.Samjna

/*
 * DSL: varnas() closure - tokenize the script into individual varnas (list)
 */
String.metaClass.varnas = {
  new SimpleScriptScheme().tokenize(delegate)
}

/*
 * DSL: halantyam() closure - remove the last hal iT and return the modified String
 */
String.metaClass.halantyam = {
  ItRules itRules = ItRules.instance
  def varnas = delegate.varnas() as List
  if (itRules.hasHalantyam(delegate)) {
    varnas.remove(varnas.size()-1)
  }
  varnas.join()
}

/*
 * DSL: tasyaLopah() closure - remove all the it-markers from a pratyaya
 */
String.metaClass.tasyaLopah = {
  ItRules itRules = ItRules.instance
  itRules.tasyaLopah(delegate)
}

/*
 * DSL: Direct exposition of a pratyaya or a pratyahara!
 */
SivaSutra sivaSutra = SivaSutra.instance
sivaSutra.metaClass.getProperty = { String pratyahara ->
  def metaProperty = SivaSutra.metaClass.getMetaProperty(pratyahara)
  def result
  if(metaProperty) {
    //if there is an existing property invoke that
    result = metaProperty.getProperty(delegate)
  } else {
      //inspect the property and convert it to varnas
    //taparastatkaalasya rule; need to formulate in a better way
        if (pratyahara.endsWith('t.')) {
      result = (pratyahara - 't.').varnas()
    } else {
        result = sivaSutra.collect(pratyahara)
    }
  }
  result
}

void testSivaSutra() {
  SivaSutra sivaSutra = SivaSutra.instance

  sivaSutra.table.each { println it } //print the maheshvara sutrani
  println sivaSutra.list //print a flattened version of the maheshvara sutrani
  sivaSutra.each { println it } //another way to print flattened maheshvara sutrani
  println sivaSutra.itMarkers //print only the it markers

  assert sivaSutra.isIt('n.') //check if n. is an it marker

  assert sivaSutra.expand('ak') == ['a','e','u','N','r.','l.','k'] //expand pratyahara including the it
  assert ['a', 'e', 'u']== sivaSutra.collect('ak') //pratyahara excluding iT
  assert ['a', 'e', 'u']== sivaSutra.ak //another way of getting the pratyahara! Meta-programming in play!
}

void testItRules() {
  ItRules itRules = ItRules.instance

  println itRules.ajanunasika //prints all the ac anunasikas
  assert "lyut".varnas() == ['l', 'y', 'u', 't']}


void testHalantyamRule() {
  //print the pratyahara-s after the halantyam rule applied
  ["kt.va", "Gan.", "kt.vat.", "sap", "lyu-t", "saN", "sat.r."].each { println it + " = " + it.halantyam() }

  assert 'kt.va' == 'kt.va'.halantyam()
  assert 'kt.va'  == 'kt.vat.'.halantyam()
  assert 'Ga' == 'Gan.'.halantyam()
}

void testTasyaLopahRule() {
  ["Gan.", "kt.vat.", "sap", "lyu-t", "saN", "satr."].each { println it + " = " + it.tasyaLopah() }

  assert 'a' == 'Gan.'.tasyaLopah()
  assert 't.va' == 'kt.vat.'.tasyaLopah()
}

void testSamjnaSutras() {
  SivaSutra sivaSutra = SivaSutra.instance
  
  def vruddhi = sivaSutra.'At.' + sivaSutra.ic
  def guna = sivaSutra.'at.' + sivaSutra.'E.n'

  assert ['A', 'i', 'O.'] == vruddhi
  assert ['a', 'E.', 'o'] == guna
}


testSivaSutra()
testItRules()
testHalantyamRule()
testTasyaLopahRule()
testSamjnaSutras()

[Listing 4: SimpleScriptScheme.groovy]
package ch8.schemes

/**
 * A simple script tokenizer
 * 
 * @author vsrinivasan
 */
class SimpleScriptScheme implements ScriptScheme {

  // hyphen denotes anunasika
  static List NotationMarkers = ['.', ':', '-']

  /** 
   * split/tokenize a given word into a list of varnas
   * the word could be a pada, shabda, pratyaya or pratyahara
   * needs to handle anunasika properly
   * 
   * @calledby String.metaClass.varnas()
   * @param word
   * @return list of varnas
   */
  @Override
  public List tokenize(String word) {
    def varnas = []
    word.eachWithIndex { c, i ->
      c = ((i < word.length()-1) ? ((word[i+1] in NotationMarkers) ? (c + word[i+1]) : c) : c)
      if (!(c in NotationMarkers)) varnas << c
    }

    varnas
  }
}


Now some observations and analysis:

  1. To do this in a regular Java/C# would require several objects, wrapper-classes and utility methods to be created. But using meta programming techniques and defining a clean DSL makes this a very interesting implementation.
  2. Ability to work directly on strings, lists and maps makes a huge difference, as opposed to wrappers around strings and creating objects like pratyahara, it, pratyaya etc.
  3. The Main.groovy is self-explanatory in what's given and what's expected. This is not pseudo-code anymore! Note the direct method invocation like varnas(), halantyam(), tasyaLopah() on Strings. And also observe the direct reference to a pratyaya (sivaSutra.ac will expand to a list of vowels). Metaprogramming, awesome or what?
  4. Also observe the testSamjnaSutras() definitions. The only reason I have to quote the properties is due to the usage of dot in the schema. A symbol-less scheme like AST would make a very readable code.
  5. The code uses the SimpleScript for devanagari transliteration. As I had mentioned in a previous post, parsing the script is trivial, because of a strict 1:1 mapping between English and Sanskritam letters. Took less than 5 minutes to write it.
  6. However the code allows to use any transliteration scheme, if one can come up with it, by implementing the ScriptScheme interface. Harvard-Kyoto, ITRANS or AST or even Unicode - as long as the individual varna-s are correctly tokenized, the program will work fine.
  7. Any script scheme can be supplied via a groovy configuration and read by ConfigSlurper!
Obviously this is just the very beginning and some areas are still unpolished. But imagine being able to write code like

assert "bhavati" = bhU + sap + tin //1st gana
assert "kasca" == 'ka:' + sca //scutva sandhi

Imagine being able to work out sandhis just by using the plus sign! (eg ) Wouldn't that be really really cool? And that's not really impossible. It will only take a little more effort to expand the DSL to include anga, guna, operator overriding for sandhi rules etc.!

Imagine similar DSL-s can be implemented for parsing shlokas to determine chandas! The potential for a Samskritam DSL is huge.

Tuesday, November 15, 2011

Read, Restore and so forth

My first sight of a computer was in 1983 in a remote town in India, the deity of the city is a representation of "Conscious-Ethereal Grand Cosmic Nothingness". Our science teacher somehow got hold of somebody who had a Commodore 64. About 40 students from our class (India was that less populous 30 years ago) walked about 5 kilometers on a rainy day to that computer guy's house. We were allowed in a batch of 10 into a room dimly lit and were seated on the floor. A girl, sitting on the chair, was holding a joystick (or a mouse?) and a keyboard and making a noisy typing sound. On the small monitor some rectangles and squares of different colors were jumping around. She was playing some game. She said something about BASIC and thats all we learnt.

Almost 10 years forward. It was the onset of the Russian winter, I was walking with a senior towards the university. He was a smart guy, everybody respected him and was always an A-grader.  We were talking about programming language theories. C++ was just getting popular. He said "Hey, I know Pascal and C. And this year we are learning some AI using Prolog. I've also been learning C++...". He paused. Then suddenly said, "You know BASIC right? Can you teach me that?". I didn't know what to respond, but just said "Sure". I was a bit confused but elated to 'teach' a senior. That opportunity never came though.

Current times. Studying Ashtadhyayi's several techniques which are an illuminating parallel to programming - there is one that is intriguing. It is the word "aadi" given in a context. When Panini wants to mention a group of information, he would just use the first value of the group and suffix it with "aadi" or "aadya:". The reader is obviously either expected to know the list by-heart or refer to it. No big deal, when the average Sanskrit student is expected to know amarakosha by-heart anyway. So the first value of the list itself is used as the "head" to reference the list. This way Panini feeds by a pointer to an array of data using a very simple technique.

A pseudo code may clarify:

/* The list of verbs called as dhaatu paatha */
static Map DHAATU_PAATHA = [bhU:sattaayaam, ... ]

/* pointer to the list of the dhaatu paatha; trying to mimick naturalness - intentionally not referring via the static variable but via the head-value of the list */
char *list_of_verbs = ["bhu"]

Look at some of the sutra-s -

bhUvAdayo dhaatavaH (1.3.1) | By this statement Panini refers to about 2000+ verbal roots in Sanskritam, starting with bhU
sanaadyantaa dhaatavaH (3.1.32) | Refers to the list of derivational roots, the list starts with a verb that ends with suffix "-san"
praadayaH | Refers to the 22 prepositions that start with "pra"

Obviously this technique of "aadi" reference is pretty common in Sanskritam and other Indian literature. Tyagaraja in his siddharanjani kriti naadatanumanisham says "sadyojaataadi pancha-vaktra" referring to the five faces of Shiva starting from sadyoja. Obviously one who is not aware of the details will not know what the rest are, but aadi is just what it is - a pointer to a list of information. If Panini was the one who invented it (lets assume for sake of argument, because Panini had predecessor grammarians too and there were obviously other literature before him), it is a brilliant technique. The technique is not perfect though, because overtime somebody could come up with a modified list with the head-value being the same. But still its a great way to abstract information where the uniqueness of the head-value serves as an emphasised indicator to the contents following it.

Back to programming after the detour. Even after several years in programming, BASIC continues to fascinate me. Given all kinds of high level languages, there is one feature I think I sorely miss from BASIC. It is the "READ...DATA" statement. The READ...DATA statement allows for feeding data to the program in the shortest possible way without having to assign random values individually.

10 FOR I = 1 TO 10: READ X(I): NEXT I
20 DATA 1,3,5,7,11,13,17,19,23,29
30 RESTORE 20

10 READ NAME$, PHONE$, PI, BASERADIX
20 DATA "James Bond", "555-1212", 3.14, 8
30 DATA "11/11/2011", "All the world's a Pre-Production."
50 READ DATE$, WS_QUOTE$

The DATA statement could be anywhere in the program and the READ statement would sequentially read-off the data, like popping off a stack. The RESTORE statement acts like just like the "aadi" of ashtadhyayi - it points to just the beginning of the data. The simplicity of the bootstrap data feed is appreciated when you do not care where the DATA is set. Several high level languages have been invented after that, but not many provide such an easy way to feed bootstrap data to the program variables. Of course there is enumerators and similar stuff, but somehow the simplicity of READ statement stands out. Just like Panini's aadi technique.

Tuesday, August 9, 2011

Six degrees of Sutras

One of the memorable humour tracks of Tamil movies is from arivAli (The Intelligent) made in early 1960s. A black white film, with simple clean humour. Very likely such movies were made in other Indian languages too. The husband asks his wife to make puri. Wife does not know how to make it, so husband gives instructions to her:

Husband: Take a vessel and put some wheat flour in it
Wife: Yeah, I know that!
Husband: Pour some water and salt and mix with flour
Wife: Yeah, I know that!
Husband: Make it into small round balls
Wife: Yeah, I know that!
Husband: Flatten it and make it round like appalam
Wife: Yeah, I know that!
Husband: Then what?
Wife: Aah, I dont know that...


In an earlier post we saw how a sutram's definition can be applied to naming convention of variables in modern programming context. A natural question arises - what are the types of sutram-s? As I have mentioned before, classification is ancient Indians' forte. There are six types of sutram-s which is defined, yeah you guessed it, in a shloka:

संज्ञा च परिभाषा च विधि: नियम एव च ।
अतिदेशो अधिकारश्च षड्विधम् सूत्र-लक्षणम् ॥


A lot has been described about this classification in wiki articles and elsewhere. Here we will just look at the parallels between this classification and programming concepts.
संज्ञा - definition; परिभाषा - interpretation; विधि- rules; नियम - restriction; अतिदेश- extension; अधिकार - header/domain.

संज्ञा is a definition sutram. It gives a meaningful name for one or more symbols. Do you remember your early programming days where you are told that a good practice is to give a name for constants? (Do you still follow that?)
 

वृद्धिरादैच् |  [1.1.1]  {a, e, o} are called vRuddhi |
 

In programming terms, this is like the classic C #define statement or final static/const statements in Java/C# world. 

#define PI 3.14

#define IK_PRATYAHARA {i, u, Ru, Lu}


परिभाषा sutram is an interpretation or meta-rules sutram. Its function is to tell how to interpret other sutram-s.
      
तस्मात् इति उत्तरस्य | [1.1.67] When a sutra has a word in panchamI vibhakti, then the word next to it will undergo some modification. 


A very good equivalent to interpretation rules is Annotations. This example will make it clear:


@WebMethod(POST)
public void updateUser() {
}


The annotation says that the method updateUser() must respond to only a http post call. It helps the runtime interpret the method in a certain way.

विधि sutram: What is the fundamental difference between a calculator and a computer? The calculator (a regular) deals with numbers only, while the computer can make logical decisions.

विधि sutram is the classic if-else-condition. In fact, the way पाणिनि has applied it - its closer to aspect-based rules than just a vanilla if-else condition. There is a slight difference between "if do this" and "when apply this". While the if-condition has to be encountered during the execution process thread, a when-rule applies anytime during the happening of a certain condition. "if" is thread-execution based, while "when" is time based, a trigger with an "if".पाणिनि defines several rules in his अष्टाध्यायी. For example there is a famous sandhi rule with just three words, that covers a matrix of sandhi-s.
       
इको यण् अचि | [6.1.78]
When a vowel follows, the letters i, u, Ru, Lu change to y v r l.

Obviously any if-else condition would be a vidhi sutram. If we were to follow paaNini's technique, we would not write it as a simple if condition. Instead we would define all "when rules" in a separate section of the code, and provide aspects of applying. When code executes, the aspects will monitor the code and "apply" a rule when those conditions are satisfied. For eg the (now) Oracle's Haley is one of the very popular Rules Engine products, in which Rules can be defined in simple English.

नियम sutram
If programming was based on socialistic ideologies, rules would apply uniformly to all cases (except the political class, of course). But reality is somewhat capitalistic, so there is always some case which disagrees to agree. Remember the business requirements like "should apply to all but one or two cases" and the complex if-conditions you would have to write to handle just the boundaries?

Restriction is not Exception. Exception is an alternative flow, but restriction is about applying a rule to a lesser number of or rarer cases. In general, it is achieved by if-else conditions, but doesn't always have to be so.

अतिदेश sutram-s are extensions. They qualify a pre-existing rule with another property, not originally possessed.
   
Using pratyaya-s vat and mat, paaNini extends the behaviour of one rule and applies to another rule.
       
लोट: लङ्वत् | [] would mean "लोट् vibhakti-s are to be conjugated just like लङ्"
       
Imagine that
लोट्, लङ् etc implement an interface called "ल". Panini's technique essentially casts लोट् as लङ्.
       
Class extensions are very common in OO languages. Using the Extension mechanism offered by Ruby, C# etc, one can improve the functionality of an existing class. For eg, String class does not have intrinsic methods to check if the value is null or empty . One could add a IsNullOrEmpty(this String) method and operate directly on a string instead of a new helper class.
       
It does not end there. Imagine two objects User and LockedUser:
       
User user; //normal user behaviour
LockedUser lockedUser; //a locked user behaviour, imagine a Trait (see Scala which allows partially implemented interfaces)
if (user.failedAttempts(3)) { user.setBehaviour(lockedUser)); } //user now behaves like a lockedUser

       
Instead of changing the state of the object (commonly via isLocked() or status = LOCKED), the behaviour of the object itself is changed. Upon certain conditions, the regular user adapts the behaviour of a locked user. We do not directly deal with properties and state changes, instead work with behaviour changes. For eg, Scala offers Traits, with partially implementable methods, which are much more than interfaces. In a way you are describing or coding to the behaviour of an object rather than the states.
       
अधिकार sutram: If you have done database modeling, you know Subject Areas. In programming terms, think of package, namespace etc. They all define a domain underwhich certain rules/classes/tables are grouped. Thats exactly what adhikara sutram is. More information on adhikara sutram can be found in this post.
   
संहितायाम् | []  "During the closeness of words"
प्रत्यय: | [3.1.1] "Affix"
       
package com.microsoft.office;
namespace Com.Sun.Oracle.Java;
//ok, I was being facetious :-)


Apart from these core sutram-s there are a few more.

निषेध sutram-s are negation rules of other rules. While niyama sutram-s are positive restrictions, nishedha can be seen as negative orientation.
   
हलन्त्यम् | (consonant endings are it-markers)
न विभक्तौ तुस्माः | (but
letters t, th, d, dh, s, m are not it-markers if it is used for conjugations)
       
In programming, we can come up with a validation rules engine like this:
       
1. All Address Fields Required
2. Not if Address Line 2
       
Imagine the simplicity of a program using such a validation engine!
       
विभाषा sutram is an optional rule. For eg think of the sentence "I would like to goto a movie". You can also say it as "I'd like to goto a movie". The shortening of "I would" to I'd does not change the meaning, and is optional to use. पाणिनि uses this technique to provide alternative usages of words and grammar by using the shabda-s vaa, vibhaaShaa, anyatarasyaam. Optional rules are very common and are done using if conditions.

Besides these, some of the paaNini's techniques also strike a chord with modern techniques. For eg, there is an interpretation sutra विप्रतिषेधे परम् कार्यम्, which means "In case of rule-conflicts, the latter rule prevails". Virtual override feature?

Another unique technique is called स्थानी भाव where a substituting suffix can retain the characteristics of a substituted suffix. Heard of Liskov Substitution Principle? Yeah, something like that.

Panini also uses recursive techniques for some of the rule operations. We will see that in a subsequent post.


Yet another ingenious technique is seen in the last 3 pada-s of अष्टाध्यायी where every previous rule is oblivious to all the latter rule. The rules are arranged in such a way that every rule "thinks" that it is the last rule of the book.


So what is the benefit of comparing modern programming with a 2500+ old text book of grammar? Let it be पाणिनि:, Capellini or Linguini founded algorithms. As a software engineer, what do I care? I do not have an answer. After all, a programmer consultant in US writes a for-loop for $75 an hour, while the same for loop is written by some one in China for a few Yen. Can you judge which for-loop is better?

If several of modern programming concepts have indeed parallels in अष्टाध्यायी, how about some concepts in अष्टाध्यायी not yet formulated into modern programming theories? What if they could create a fundamental change in theory of programming?

What would पाणिनि: think about modern programming concepts? To find out, we shall send Donald Knuth back in time as our representative.

Knuth: Programming is about definitions, rules and algorithms.
पाणिनि: आम्, जानाम्येव !
Knuth: Using algorithms we derive and solve various equations.
पाणिनि: आम्, जानाम्येव !
Knuth: In object oriented programming, we do abstraction, polymorphism and other cool things.
पाणिनि: आम्, जानाम्येव !

Knuth: With functional programming, we define functions, recursions and closures.
पाणिनि: आम्, जानाम्येव !
Knuth: Then we create programs to play games like Grand Theft Auto all day long.
पाणिनि: अहो ! तदहम् न जानामि !!

Sunday, July 10, 2011

Paninian Blues



The brevity of Panini's अष्टाध्यायी has been widely read, wondered, appreciated, criticized, discussed, commented and treatised over the past couple of thousand years. On one end of the Sanskritam literature spectrum are such extremely, almost ridiculously, laser-like focused and concise treatment of subjects in sutram format. On other end stand the lengthy and wordy mega-serial type works from kaadambarI, kathaasaritsaagara, yogavasiShTha (32,000 verses), raamaayaNa (24,000 verses) upto the granpa and granny of all - the mahaabhaarata (100,000) and bhaagavatam. In between are the short-stories focusing as much as possible to the main theme.

Interestingly while raamaayana contains 24000 verses, it has been retold in different variations in a wide variety of formats in different languages, since vaalmIki. In fact the very first 100 slokas contain an abridged version of raamaayaNa by vaalmIki himself. There is a Swati Tirunal's kriti "bhaavayaami raghuraamam" - the story of raama in few stanzas set in different ragas. Very recently was released a visually stunning retell of the story by Sanjay Patel. There is even a eka-shlokI-raamaayaNa which tells raamaayaNa in just one shloka!

आदौ राम तपोवनादि गमनम् हत्वा मृगम् काञ्चनम् ।
वैदही हरणम् जटायु मरणम् सुग्रीव सम्भाषणम्  ।
वाली निग्रहणम् समुद्रतरणम् लङ्कापुरि दहनम् ।
पश्चात् रावण कुम्भकर्ण निधनम् तु एतत् हि रामायणम् ॥

The transformation of a few verses to a delightful and an exquisite kaavya (eg. shaakuntalaa by kaalidaasa) or crunching a big story to a few lines like the above seems to have fascinated Sanskritam poets.

One of the most fascinating पञ्चतन्त्र story is The Blue Jackal. Hunger, sympathy, cunningness, fear, imposture, divine invocation, regality, anger, violence - so much characteristics are packed in a few verses. One can quote several movies on this pose-as-somebody-else-and-take-others-for-a-ride theme and variations. While movies of every language seem to have this kind of comedic setup, the evergreen classic Golmal (Amol Palekar) comes to my mind immediately.

But what if, instead of विष्णु शर्म, पाणिनि had written the पञ्चतन्त्र ? May be he would have reduced the pancha-tantra to pancha-paragraphs.

Lets imagine the blue jackal story, Panini-style. Let paNDita-s forgive me for such a blasphemy.

अरण्ये ।
शृगाल: ।
  - वने कश्चन शृगाल: वसति स्म ।
प्रत्याहारम् भुभुक्षाया: ।
  - स्वस्य भुभुक्षा-कारणत: आहारम् प्रति स: अन्वेषणम् अकरोत् ।
तत्र । (2.1.56)
श्वपदानुसारणात् नीलभाण्डपतितोऽपिसन् ।
    - शुनकै: खेतित: धावित: श्रुगाल: नीलभाण्डे अपतत् ।
परश्च । (3.1.2)
प्रतिपथमेति । (4.4.42)
    - तत्परम् स: वनम् प्रत्यागच्छत् ।
अज्ञाते । (5.3.30)
आत्मने चण्डरव: इति ।
दूतस्य भाग-ब्रह्मणि । (4.4.120)
    - मृगा: तम् न ज्ञातवन्त: । स: शृगाल: "अहम् चण्डरव:, ब्रह्मण: दूत:" इति कथितवान् ।
राजा च । (6.2.59)
वृन्दारक नाग-सिंह-कुन्जरै: पूज्यमान: । (2.2.62)
प्रसंशावचनैश्च । (2.2.66)
    - स्वयम् राजानम् मत्वा सर्वेषु मृगेषु भीति: उत्पादितवान् । मृगा: तं शृगालं प्रशंसवचनै: पूजितवन्त: ।
वृष्टिरादैच् ।
    - एकदा वृष्टि: आकाशात् आगता ।
अन्यैश्च टंकार: ।
    - अन्यै: शृगालै: टंकार: कृत: ।
स्वं रूपम् शब्दस्य (1.1.68)
    - तं शब्दं श्रुत्वा शृगाल: स्वस्य रूपं विस्मृतवान् ।
स्वयं तेन । (2.1.25)
    - तेन शब्देन स्वयं पुर्व-रूपं स्मृत: नीलशृगालेन अपि टंकार: कृत: ।  मृगा: तस्य शब्दस्य अभिज्ञातम् कृतवन्त: ।
हनस्च वध: । (3.3.76)
     - मृगा: चण्डरवम् मरितवन्त: । 
तस्य लोप: । (1.3.9)
    - शृगालस्य लोप: स्यात् ।
तदर्हम् । (5.1.117)
    - स: तद् अर्हति एव ।
The sutram-s with indicated numbers are either a direct lift or lousy modifications of the अष्टाध्यायी sutram-s. The वृत्ति is in blue.

Monday, December 14, 2009

The intellectual devotee

No matter how much ever one tries to embrace and love it, grammar of any language always remains a dry subject. At some point of time, the mind wants to stop analyzing and start to take things as-is. Panini's grammar rules, no doubt is a great tribute to human intelligence. At the same time, another extra-ordinary intellect, Adi Shankaracharya asks "What is the point of studying grammar, when the real liberation is achieved only by chanting the name of Govinda".
Chanting the names of Vishnu is a sure way to moksha especially in Kali yuga - Vyasa emphasises this in several of his works. The more you call his name the more the chances of liberation. So, of what use is memorizing and repeating the undecipherable technical terms of Panini - most of which does not even sound like a proper word, when the mind can be repeating the thousand names of Paramatma? Do the words like ShtunoShtu:, k~giti ca, ikoyanachi get a person any closer to moksha?
Thus the bhakta is at cross-roads with jnana. Should one study the intricacies of grammar or just chant the names of mAdhava? And why can't he do both?
A variety of literature has followed AshtadhyayI. While the SutrapATha (AshtadhyAyI) remains the ultimate focus of these literature, the literature itself spans several dimensions - vritti (gloss), vArtika (notes), bhAshya (exposition), siddhAnta (theory). Sutra was extremely concise, so vritti was written to supply missing elements. vArtika expanded the sutra, while mahAbhAshya was an extensive treatment, leaving no gaps. Kasika vritti, siddhantakaumudi, laghu siddhanta kaumudi have treated AshtadhyAyI extensively. In between there are novel attempts like BhattikAvya which attempts to teach Paninian grammar via Ramayana.
In the juggernaut of the Bhakti movement started around early 8th century (?) with Azhwars/Nayanmars and gained prominence throughout India by 15th century, someone snaps, why do I have to read all these grammar rules while I can be chanting the name of Hari? Of what use is this grammar when nitya sukham is in repeating the names of Krishna! And thus Jiva Gosvamin creates a brilliant work - 'Harinamamruta vyAkaraNam' - literally "The Grammar of Nectar of Names of Hari". It is based on Panini's grammatical rules, but every technical term is replaced by a meaningful facet of Vishnu.
Let us look at some of the parallels of Panini's technical terms and Harinamamruta vyakarana
vowels/varna/svara (ac) - sarveSvara:
first 10 vowels (ak) - daSAvatAra
each pair of vowel (hRsva and dIrgha) - ekAtmaka
hrsva - vAmana
dIrgha - trivikrama
pluta - mahApurusha
anusvara - vishnuchakra
anunAsika - vishnuchApa
visarga - vishnusarga
ka ca Ta ta pa - hari-kamalam
kha Cha Tha tha pha - hari-khadga:
ga ja da Da ba - hari-gada
Gha Jha dha Dha bha - hari-ghosha:
Adesha - virinci
Agama - vishnu
pumlinga - purushottama
strIlinga - lakshmI
napumsalinga - brahmajna
avyaya - alinga
lopa: - hara:

and so on. All the technical terms are carefully replaced by equivalent meaningful facets of Vishnu! Thus Jiva Gosvamin creates about 3192 sutras - a devotional parallel to Panini's AshtadhyAyI.

The intellectual devotee fulfils two purposes immediately - learn grammar by chanting the names of Vishnu. Talk about direct ascendency to moksha by bhakti through jnana!

Wednesday, December 9, 2009

From raama to raamaha

In a previous post we saw how a programming language can be written effectively in a natural language using Paninian sutra style.

In this post, let us do the exact opposite: converting a set of Panini-sutras to programming language style syntax to understand the rules of Sanskritam. The aim of the post is to kindle interest in Sanskrita studies for a typical software engineer to see the parallels of concepts of programming in Paninis methods. Statements and researches on Panini's methodology and how it is close to programming can be found plenty googling around. But as the ancient saying goes the proof of code is in the compiling. Of course I wont be delivering a code here, but hopefully a pseudo-code should convince any software engineer. Much of the pseudo-code can be polished and implemented in languages like Groovy/Ruby that supports expando, reflection etc.

Beginner Sanskrita students are often confused between rAma and rAma: (pronounced raamaha). Why do we add a visarga? Does the addition of visarga change the meaning?

The short answer is: Yes, the addition of visarga does add meaning.

In non-inflexional language like English, the prepositions provide the purpose of the noun. For eg by Rama, to Rama, from Rama, in Rama: in these cases "Rama" stays constant, while the prepositions provide the notion. Hindi also exhibits non-inflexional properties (rAm ne, rAm ko, rAm se, rAm par). In inflexional languages, the noun itself is modified to denote the purpose.

So what does this have to do with rAma: ? The word rAma: can be split into rAma + visarga. Here rAma is called the "stem" or "nominal stem". In Sanskrita its called prAtipadikam (प्रातिपदिकम्). prAtipadikam is defined as "arthavat adhAtu apratyaya" (अर्थवत् अधातु अप्रत्यय प्रातिपदिकम्) -- that which has meaning, and not a root, and not a suffix is called prAtipadikam. This stem will undergo modifications (inflexions) to fulfill the purpose of the noun.

Panini provides the methodology of modifying stem "rAma" to "rAma:" in a few sutras.

  1. su aujasamauTChasTAbhyAmbhis~gebhyAmbhyas~gasibhyAmbhyas~gasosAm~gyossup
  2. upadeSe ajanunAsikA it
  3. sa sajuSho ru:
  4. kharAvasanayo: visarjanIya:
The same in devanAgarI:
  1. सु औजसमौट्छस्टाभ्याम्भिस्ङेभ्याम्भ्यस्ङसिभ्याम्भ्यस्ङसोसाम्ङ्योस्सुप्
  2. उपदेशे अजनुनासिका इत्
  3. स सजुषो रु:
  4. खरावसनयो: विसर्जनीय:

Forget the tongue-wrecking, memory-bending first sutra for now. We will see its utility in the future posts.

Lets do some pseudo-code now.

//purpose of the noun - what do we want? singular/plural, masculine/feminine etc.
def purpose
//the stem to use, based on the purpose, this stem will now change
def stem = "rAma"
//anunAsika vowels for #2 (using single quotes to denote nasalization)
def nasalVowels { a', A', i', I', u', U', R', R.', e', ai', o', au' }

//Requirement: create a nominative-singular-masculine form of rAma -- prathamA vibhakti, ekavachanam, pumlinga from prAtipadikam rAma

def create_nominative_singular_ masculine_noun_from_stem(stem) {

if (purpose.isMasculine()  && purpose.isSingular() && purpose.isNominative()) stem.append("su'") //sutra #1: rAma -> rAmasu'
if (stem.endsWith(nasalVowel)) stem.removeLast(nasalVowel) //sutra #2: rAmasu' -> rAmas
if (stem.endsWith("s")) stem.replace("s", "ru'") //sutra #3: rAmas -> rAmaru'
if (stem.endsWith(nasalVowel)) stem.removeLast(nasalVowel) //sutra #2: rAmaru' -> rAmar
if (stem.endsWithAnyOf(KHAR)) stem.replace(stem.findLast(KHAR), ":")) //sutra #4
return stem //rAma:
}
Following the algorithmic steps, when the intention of one rAma is to be in nominative case (or as a subject), the end result is that a visarga is appended. Just 'rAma' does not denote anybody. "rAma:" denotes one masculine person in nominative/subject form.

Naturally, a question arises - Why dont we just add a visarga at the end instead of going thru all these rules? Note that this visarga is only for a masculine form. For neuter and feminine nouns, a su' will be added, but other rules from prevent them into morphing into a visarga. So Panini adds a common suffix and specifies rules on how it is applied in various situations.

In the next post, let us look at making the above method efficient.

Thursday, November 19, 2009

Sutra based Programming

Haven't software engineers had enough of programming languages? C and C++ were there for a while unchallenged. Then Java took over C/C++ pretty quickly. Even though you could create complex applications using Java and run on any platform, there is no dearth of new languages. Scala, Groovy, Ruby and very recently Go from Google.

All high-level programming languages do 4 basic things:

  1. Assignment
  2. Condition
  3. Loop
  4. Function/Procedure.
Loop and Function/Procedure/Subroutine are essentially glorified Goto.

Everything else is syntactic sugar.

Galileo has influenced us heavily to think math in terms of symbols. A mathematical symbol expresses an idea very concisely and effectively. Much more than a language could do.

So

x = 1
is more concise than saying "let x equal to 1".

Let me rephrase the above bereft of assumptions --


The mathematical expression "x = 1" is more concise than saying it in English "let x equal to 1".

But what if we could express "x = 1" much more concise in a natural language?

For e.g., let me just say

x 1
I just dropped the symbol "=". One symbol less! Whohoo! I also established a convention that whatever on left side is receiver and on the right side is provider. In a language like Sanskrit, for e.g., the "is/happens" is implicit (asti/bhavati). So no other verb is required. (There are other languages that exhibit this property too).

People think that just because ancient Sanskrit mathematicians did not use symbols, the works are not scientific. Symbol is just a convenience; if language could be more powerful than symbols, who needs them? As a side note, Sanskrita almost does not use punctuations (except for end of sentence - the pipeline character |). In contrast, English just can't be "communicated" without appropriate punctuations' usage.

To demonstrate the power of the language, let us look at a simple program using a pseudo-language.

//Pseudo-code to produce a random number and determine if its odd or even
s = 100;
r = (int) rand(s);
if (r % 2 == 0)
return "even";
else
return "odd";
The question is, can this program be expressed using natural language? Of course, we can write the whole program in plain English, but it wont be concise. (COBOL anyone, hello?)

Now lets apply the Sanskrit grammarian Paninian rules. I am going to keep the function names as is (in bold), but conjugate the variable names per Sanskrit rules (taking them to be consonant ending variables).


1: aSeSha: SUnyam  // No remainder 0 (No remainder equals 0)
2: s Satam         // s Satam asti (s is 100)
3: sa: rand r      // of s random is r (r is random of s)
4: int ca          // int also (r is also int of random of s)
5: even ra: aSeshe dvibhAjane  // "even" is of r during division of 2 when no reminder happens (on division by 2 of r has no reminder, it is even)
6: odd SeShe       // "odd" when there is a reminder

Here are the sutras in proper Sanskrit:

अशेष: शून्यम् |
स् शतम् |
स: वृथा र् |
अभिन्न: च |
समं र: अशेषे द्विभाजने |
विषमं शेषे ||

As you can see there are absolutely no mathematical symbols! A program is written purely by the expressive power of language. So what happened? How are they equal?

Using nominative case and the implicit "is", Panini eliminated the need for equals sign. Functions are defined via genetive case. Using the locative case, Panini provides the if-else condition. In effect, mathematical expressions are substituted by simply conjugating the variables.

That is the genius contribution of Panini to Sanskrita! Now a skilled poet could come and rearrange the above 6 sutras into a sloka format, and lo! there is sloka that tells us how to determine an even/odd number!

Let me attempt a half-baked sloka (May Sanskrita enthusiasts forgive me for such a blasphemy).

अशेषो शून्यं भूयात् सेकशतं वृथा रेफ: स: ।
अभिन्नश्च द्विभाजने विषमं समं शेषोऽशेषे ॥

Due to the occurrence of words like SeSha, SUnyam, aSeSha, dvibhAjane, abhinna the above can be mis-interpreted to refer Adisesha, SUnyavAda, Vishnu, Dvaita, Advaita etc. Now we have an example of a sloka referring to the gods and a mathematical algorithm encoded in it!

Tuesday, November 10, 2009

The Panini Certificate

Ever since Panini has written his monumental ashtadhyAyI, there have been plenty of commentaries on it and still continues to follow. Katyayana's Vartika, Patanjali's Mahabhashya, Kasika Vritti, Siddhanta kaumudi, Laghu kaumudi, Laghu siddhanta kaumudi are a few Sanskrit commentaries. When the West discovered Sanskrit, more commentaries sprang up.

For some reason, whosoever has tasted a little bit of Panini (not the Italian sandwich) feels so compelled to write a commentary on it. In modern days blogs have replaced commentaries. Whosoever even just heard about Panini, is compelled to write a blog about him. Just like me.


Kalidasa describes this feeling in a beautiful poem:


मन्द: अपि अमन्दताम् एति संसर्गेन विपश्चित: । (मालविकाग्निमित्रम् 2.7)

The company of the intelligent brings respect even to the dumbwitted. (Malavikagnimitram - Ch 2, verse 7)


The human mind tends to super-impose the characteristics of an associative object with the associating subject. So whoever reads Homer is a literat. Whoever likes Homer Simpson is dumb. Whoever loves Bambi is cute, whoever appreciates legumes are nuts. During a Panini study, a student undergoes one or more, usually all, emotions of bewilderment, amazement, overwhelmingness, stunning and finally dumbfounded, in any order. By this time he/she figured out that he/she got smarter just knowing Panini.


Ignorance shadows smartness.
Ankle deep into ashtadhyAyI, the student now questions Panini's sutras and methodology. 'This sutra does not make sense', 'This sutra could have been avoided and put elsewhere', 'This is an unfortunate sequence of sutras' etc - so the student passes judgement like my wife's hand distributes neighbor's ghee to everybody.


When does this feeling stop? When does the student hear the inner-voice 'Oh, shut up'? The post-Panini period was a cauldron of grammatical activities. It has been told that several grammarians attempted modifications, additions of sutras to ashtadhyAyI. In midst of all this, one great intellectual, one that the human mind has since not surpassed, stood up and proclaims "ashtadhyAyI is perfect beyond your pea-brained comprehension faculties".


And that brings this quote from that Great Rishi Patanjali himself, who drank ashtadhyAyI as easily as soda from a can and gives an 'Outstanding' certificate to Panini.


tatra aSakyam varNena api anarthakena bhavitum, kim punariyatA sUtreNa |


तत्र अशक्यम् वर्णेन अपि अनर्थकेन भवितुम्, किम् पुनरियता सूत्रेण ।

Even by a single letter (varNena api) is not possible (tatra aSakyam) to exist (bhavitum) meaningless (anarthakena), what to say about a whole sutra!