, ,

I’m doing function composition in Scala using Sanskrit as a language of representation.  The two functions वर्ग (square) and द्विवारम् (twice) are combined using compose (सम्भरति) and andThen (तदनन्तरम्), so that I can construct two Sanskrit sentences (please excuse my Sanskrit Grammar):

  • वर्ग तदनन्तरम् द्विवारम्
  • द्विवारम् सम्भरति वर्ग

In Scala, we can have aliases for types and static methods – for example one can do:

import java.util.{Map => JMap}
import System.out.{println => show}

However, I could not find a way to import method aliases in Scala, so I resorted to delegation using implicits.  I’ve used FunctionOps to achieve this:

// Alias println  
import System.out.{println => दर्शय}

// square
val वर्ग = (x: Double) => x * x
दर्शय(वर्ग(3.0))   // 9.0

// twice
val द्विवारम् = (x: Double) => 2 * x
दर्शय(द्विवारम्(2.0)) // 4.0

// Delegate
implicit class FunctionOps[-T, +R](f: T => R) {
  def सम्भरति[A](g: A => T): A => R = f.compose(g)
  def तदनन्तरम्[A](g: R => A): T => A = f.andThen(g)

import scala.language.implicitConversions
object FunctionOps {
  implicit def apply[T, R](f: T => R) = new FunctionOps[T, R](f)

import FunctionOps._

val वर्गचद्विवारम् = वर्ग तदनन्तरम् द्विवारम्
दर्शय(वर्गचद्विवारम्(3.0)) // 18.0

val द्विवारम्चवर्ग = द्विवारम् सम्भरति वर्ग
दर्शय(द्विवारम्चवर्ग(3.0)) // 18.0

Now, in Sanskrit the sentences are usually are Referentially Transparent (RT). For example, the sentences द्विवारम् सम्भरति वर्ग and वर्ग सम्भरति द्विवारम् are RT. Even though, the order of words have changed, the meaning of the sentences does not change. In programming, function composition is not commutative f ⨁ g != g ⨁ f and hence writing द्विवारम् सम्भरति वर्ग and वर्ग सम्भरति द्विवारम् will produce a different output. So we have dissonance between the spoken and the executable language.

However, not all sentences in Sanskrit are RT, lets take the sentence वर्ग तदनन्तरम् द्विवारम्, because of the use of the word तदनन्तरम् there is order in the sentence, so वर्ग तदनन्तरम् द्विवारम् and द्विवारम् तदनन्तरम् वर्ग mean different things and programmatically produce different outputs as well. So we have resonance between the spoken and the executable language.

So this brings me to a question – How can I write something that resonates in meaning and execution?