RESTful Life?


The raw form of the poem just came to me without explicit act of thinking about it. I’ve then refactored and gotten it reviewed, improvised it further today to its near-to-final shape!

Life seeking many things, but instead getting a 404 NOT FOUND,

Expecting things to be 200 OK, but ending up in a 500 INTERNAL SERVER ERROR,

Pivoting our seeking and efforts, we do a 307 TEMPORARY or a 308 PERMANENT REDIRECTION

But life starts responding with 206 PARTIAL CONTENT and 207 MULTI-STATUS RESPONSES from our earlier seekings

Seeds sown culminate in a 201 CREATED through infinite seekings and progressive meanderings!

Making your program spicy – Currying & Partial Function Application (PFA)

Tags

, , ,


Languages like Clojure don’t have currying, but PFA, where has Haskell currying and not PFA; Scala has both and Groovy wants you to call methods like curry(), rcurry() or ncurry() and lo! Java (Java13 is latest as of this post) has neither.

This year at Functional Conf 2019, on the Bootcamp day for the JVM track, I took to a live demo of currying and partial function application. Starting with the overview of the concept in Java, I showed a practical DI example, how to make our own curry/uncurry and using PFA showed how to curry library functions. Followed it by live coding in different languages

Code is on https://github.com/DhavalDalal/FunctionalConference-2019-Currying-PFA-Demo.

Slides are on https://www.slideshare.net/DhavalDalal/currying-and-partial-function-application-pfa:

Booting Into Functional Programming


This year at Functional Conf 2019, on the Bootcamp day for the JVM track, I started with a 90-min whirlwind tour of the FP land primarily meant for developers wanting to embark on their functional programming journey – Booting into FP. Java was used to understand most of the concepts, however, where it fell short to explain certain concepts, I used Scala to demonstrate it and additionally used Haskell to bring about compare and contrast.

Code is on https://github.com/DhavalDalal/FunctionalConference-2019-Booting-Into-FP-Demo.

Slides are on https://www.slideshare.net/DhavalDalal/booting-into-functional-programming:

Few extension methods on IEnumerable, Func, Predicate, and IDictionary that I found useful


I found it helpful to add these extension methods on while doing Functional Programming in C#.

  • IEnumerable
  • Func
  • Predicate
  • IDictionary

IEnumerable Extensions

Lets start with IEnumerable extension methods. But before that, below are the usage examples of each of these extension APIs:

Doing Side-effect on each value (single-valued or a 2-element-tupled enumerable)

// Single-Valued
string [] names = { "Brahma", "Vishnu", "Mahesh" };
names
  .Select(name => name.ToUpper())
  .ForEach(Console.WriteLine);
// BRAHMA
// VISHNU
// MAHESH

//2-element-tuple
IList alphabets = new List { 'a', 'b' };
IList numbers = new List { 1, 2 };
IList combinations = new List();
foreach (var alphabet in alphabets) {
  foreach (var number in numbers) {
    combinations.Add((alphabet, number));
  }
}

combinations
  .ForEach((a, n) => Console.WriteLine($"({a}, {n})"));
// (a, 1)
// (a, 2)
// (b, 1)
// (b, 2)

Peeking each value

var result = "all mimsy were the borogoves and the momeraths"
  .Split(" ")
  .Peek(word => Console.WriteLine($"Where({word})"))
  .Where(word => word.Length < 4)
  .Peek(word => Console.WriteLine($"Select({word})"))
  .Select(word => word.ToUpper())
  .Aggregate("", (acc, elem) => acc + " " + elem)
  .Trim();

// Where(all)
// Select(all)
// Where(mimsy)
// Where(were)
// Where(the)
// Select(the)
// Where(borogoves)
// Where(and)
// Select(and)
// Where(the)
// Select(the)
// Where(momeraths)

Console.WriteLine(result); // ALL THE AND THE

Producing infinite values using Iterate and Generate

// Using Iterate
bool IsPrime(int number) {
  return IEnumerableExtensions.Iterate(2, x => x + 1)
    .Take(number)
    .Where(n => n  number % n != 0);
}
   
Console.WriteLine(IsPrime(2)); // True
Console.WriteLine(IsPrime(3)); // True
Console.WriteLine(IsPrime(4)); // False

// Using Generate
string Captcha(int howMany) {
  var random = new Random();
  return IEnumerableExtensions.Generate(() => random.Next(65, 123))
    .Where(integer => Char.IsLetter((char)integer))
    .Select(integer => (char)integer)
    .Take(howMany)
    .Aggregate(new StringBuilder(), (acc, elem) => acc.Append(elem))
    .ToString();
}

Console.WriteLine(Captcha(4)); //RVkn, Ccmo etc... each run produces different output.

Scanning reduction

// Using Scan to print Running Sum
new List { 1, 2, 3, 4 }
  .Scan(0, (acc, elem) => acc + elem)
  .ForEach(Console.WriteLine); 

// 1 
// 3 
// 6 
// 10

De-constructing an IEnumerable

var (first, second, third, rest) = new List { 1, 2, 3, 4 };
Console.WriteLine($"First = {first}");   // 1
Console.WriteLine($"Second = {second}"); // 2
Console.WriteLine($"Third = {third}");   // 3
Console.WriteLine($"Rest = {rest}");     // IEnumerable of remaining elements.

Maximum and Minimum By a key

var people = new [] {
  new { Name = "Eina", Age = 10 },
  new { Name = "Mina", Age = 15 },
  new { Name = "Dika", Age = 19 },
  new { Name = "Tika", Age = 10 },
  new { Name = "Maka", Age = 28 },
  new { Name = "Naka", Age = 35 },
  new { Name = "Saka", Age = 28 },
  new { Name = "Taka", Age = 45 }
}.ToList();

Console.WriteLine("*** Eldest person ***");
Console.WriteLine(people.MaxBy(p => p.Age)); // { Name = Taka, Age = 45 }
Console.WriteLine("*** Youngest person ***");
Console.WriteLine(people.MinBy(p => p.Age)); // { Name = Eina, Age = 10 }

Finally, here is the IEnumerable extension class which implements all the above APIs.

static class IEnumerableExtensions {
  // Doing Side-Effects
  // Single-Valued
  public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action) {
    if (@this == null)
      throw new ArgumentNullException("Require non-null source!");

    if (action == null)
      throw new ArgumentNullException("Require non-null action!");

    foreach (T item in @this) {
      action(item);
    }
  }
  // 2-element-tuple enumerable
  public static void ForEach<T1, T2>(this IEnumerable<(T1, T2)> @this, Action<T1, T2> action) {
    if (@this == null)
      throw new ArgumentNullException("Require non-null source!");

    if (action == null)
      throw new ArgumentNullException("Require non-null action!");

    foreach (var item in @this) {
      action(item.Item1, item.Item2);
    }
  }

  // Peek (but don't do side-effect)
  public static IEnumerable<T> Peek<T>(this IEnumerable<T> @this, Action<T> action) {
    IEnumerable<T> PeekedEnumerable() {
      foreach (T item in @this) {
        action(item);
        yield return item;
      }
    }
    
    if (@this == null)
      throw new ArgumentNullException("Require non-null list!");

    if (action == null)
      throw new ArgumentNullException("Require non-null action!");

    return PeekedEnumerable();
  }

  // Produce Infinite values using functions.
  public static IEnumerable<T> Iterate<T>(T inital, Func<T, T> next) {
    var nextValue = inital;
    while(true) {
      yield return nextValue;
      nextValue = next(nextValue);
    }
  }
  
  public static IEnumerable<T> Generate<T>(Func<T> generator) {
    while(true) {
      yield return generator();
    }
  }
  // Deconstruction
  public static void Deconstruct<T>(this IEnumerable<T> @this, 
    out T first, out IEnumerable<T> rest) {
    if (@this == null) {
      throw new ArgumentException("Collection cannot be null!");
    }
    first = @this.First();
    rest =  @this.Skip(1);
  }
  
  public static void Deconstruct<T>(this IEnumerable<T> @this, 
    out T first, out T second, out IEnumerable<T> rest) => 
      (first, (second, rest)) = @this;
  
  public static void Deconstruct<T>(this IEnumerable<T> @this, 
    out T first, out T second, out T third, out IEnumerable<T> rest) => 
      (first, second, (third, rest)) = @this;
  
  // Scanned Reduction
  public static IEnumerable<U> Scan<T, U>(this IEnumerable<T> @this, U identity, Func<U, T, U> func) {
    IEnumerable<U> ScannedEnumerable() {
      var acc = identity;
      foreach (var item in @this) {
        acc = func(acc, item);
        yield return acc;
      }
    }
    return ScannedEnumerable();
  }
  // Minimum and Maximum by a key  
  public static T MinBy<T, Key>(this IEnumerable<T> @this, Func<T, Key> selector) {
    if (@this == null)
      throw new ArgumentNullException("Require non-null list!");

    if (selector == null)
      throw new ArgumentNullException("Require non-null selector!");
    
    var minimum = @this.First();
    var minKey = selector(minimum);
    var comparer = Comparer<Key>.Default;
    foreach (var item in @this) {
      var currentKey = selector(item);
      if (comparer.Compare(currentKey, minKey) < 0) {
        minKey = currentKey;
        minimum = item;
      }
    }
    return minimum;
  }
  
  public static T MaxBy<T, Key>(this IEnumerable<T> @this, Func<T, Key> selector) {
    if (@this == null)
      throw new ArgumentNullException("Require non-null list!");

    if (selector == null)
      throw new ArgumentNullException("Require non-null selector!");
    
    var maximum = @this.First();
    var maxKey = selector(maximum);
    var comparer = Comparer<Key>.Default;
    foreach (var item in @this) {
      var currentKey = selector(item);
      if (comparer.Compare(currentKey, maxKey) > 0) {
        maxKey = currentKey;
        maximum = item;
      }
    }
    return maximum;
  }    
}

Function Extensions

Here are the examples of Function Composition and Currying.

Func<int, int> Square = x => x*x;
 
int Multiply(int x, int y) => x * y;

var uncurriedMultiply = new Func<int, int, int>(Multiply);
var multiplyCurried = uncurriedMultiply.Curry();
    
Console.Out.WriteLine($"multiplyCurried(2)(3) = {multiplyCurried(2)(3)}"); // 6
 
var uncurry = multiplyCurried.Uncurry();
Console.Out.WriteLine($"uncurry(2, 3) = {uncurry(2, 3)}"); // 6
    
// Express Twice in terms of multiplyCurried
int Twice(int x) => multiplyCurried(2)(x);

// Express Triple in terms of multiplyCurried
var thrice = multiplyCurried(3);
Func<int, int> Triple = x => thrice(x);
 
var st = Square.AndThen(Triple);
Console.Out.WriteLine($"st(2) = {st(2)}"); // 12
 
var ts = Square.Compose(Triple);
Console.Out.WriteLine($"ts(2) = {ts(2)}"); // 36

var twice = new Func<int, int>(Twice);
var ds = twice.AndThen(Square);
Console.Out.WriteLine($"ds(2) = {ds(2)}"); // 16

Now, lets look at the definitions of Function extension methods. All of them are Higher-Order functions.

public static class FuncExtensions {
  // Compose functions using AndThen and Compose
  public static Func<A, C> AndThen<A, B, C>(this Func<A, B> f1, Func<B, C> f2) =>
    a => f2(f1(a));

  public static Func<A, C> Compose<A, B, C>(this Func<B, C> f1, Func<A, B> f2) =>
    a => f1(f2(a));

  // Curry and Uncurry for 2-arg function
  public static Func<A, Func<B, C>> Curry<A, B, C>(this Func<A, B, C> f) =>
    a => b => f(a, b);

  public static Func<A, B, C> Uncurry<A, B, C>(this Func<A, Func<B, C>> f) =>
    (a, b) => f(a)(b);
}

Predicate Extensions

Next, lets look at Predicate extension methods. These are on similar lines to the ones found in Java. Again, all of them are Higher-Order functions.

public static class PredicateExtensions {
  public static Predicate<T> Not<T>(this Predicate<T> @this) {
    if (@this == null)
      throw new ArgumentNullException("Require non-null Predicate!");
    
    return t => !@this(t);
  }

  public static Predicate<T> And<T>(this Predicate<T> @this, Predicate<T> that) {
    if (@this == null || that == null)
      throw new ArgumentNullException("Require non-null Predicate!");
    
    return t => @this(t) && that(t);
  }

  public static Predicate<T> Or<T>(this Predicate<T> @this, Predicate<T> that) {
    if (@this == null || that == null)
      throw new ArgumentNullException("Require non-null Predicate!");
    
    return t => @this(t) || that(t);
  }
}

Dictionary Extensions

Next, lets look at IDictionary extension methods. It allows you to return a specified default value for a non-existent key in the dictionary. The two forms are:

  • Return a default value
  • Return a supplier function which then returns a default value

In case you don’t have a return value, the third form GetValueOrThrow allows you to throw an exception. Again, these are on similar lines to the ones found in Java and Scala.

public static class IDictionaryExtensions {
  public static V GetValueOrDefault<K, V>(this IDictionary<K, V> @this, K key, V defaultValue) {
    if (@this == null)
      throw new ArgumentNullException("Require non-null Dictionary!");
    
    if (@this.ContainsKey(key))
      return @this[key];
    
    return defaultValue;
  }

  public static V GetValueOrDefault<K, V>(this IDictionary<K, V> @this, K key, Func<V> defaultValueSupplier) {
    if (@this == null)
      throw new ArgumentNullException("Require non-null Dictionary!");
    
    if (@this.ContainsKey(key))
      return @this[key];

    return defaultValueSupplier();
  }
  
  public static V GetValueOrThrow<K, V, E>(this IDictionary<K, V> @this, K key, E exception) 
  where E : Exception {
    if (@this == null)
      throw new ArgumentNullException("Require non-null Dictionary!");
    
    if (@this.ContainsKey(key))
      return @this[key];

    throw exception;
  }
}

Hope you find these useful in your day-to-day work!

Why Workshops are not “trainings”?


As practiced today largely in the context of Information Technology companies, I have found it necessary to delineate these two words – Workshop and Training. Hence this post.

The word “training” as the dictionary expounds is – the action of teaching a person or animal a particular skill or type of behaviour“ and it is in same sense that everyone understands this word. Similarly, the word “workshop” as the dictionary expounds is – a meeting at which a group of people engage in intensive discussion and activity on a particular subject or project. Now herein lies the big difference – workshop’s multi-directional nature of engaging people in such a manner creates opportunities for deep reflection, realisations and learnings that stick, which other-wise would be difficult in trainings, largely due to its uni-directional or at best bi-directional nature.

Human evolution as it stands today – many experience that mind is not fully under its own control; many a times emotions hijack its operations or annul its decisions. Even if we were to bring about this control, cultivating it is like working on the hardest terrain on the earth – the rocks! So, how can I inspire you to work on this hardest terrain? Workshops! To bring about a mind-shift is what workshops have the potential to achieve. Mind-shift (inspiration) can easily trigger control and cultivation. In my view, trainings have a very limited scope of bringing about this mind-shift, as its primary focus is on developing particular skills.

Why workshops?

Activities and discussions in a workshop immerse and involve people intensely, learning happens as they experiment and build it themselves. As activities and guidance untie the knots and unblock it, the mind will interest itself in drawing inferences from the facts, tracing cause and effect. An adept facilitator can then lead the audience to notice successes and failures and the reasons behind them. This approach shows where the knowledge lies and how can it be habituated to rise to the surface, rather than knowledge being imparted as information being supplied from outside1 (a.k.a trainings). As Sri Aurobindo puts it in his Integral Education Principles that the first principle of teaching is that – “Nothing can be taught.” I’m also reminded of these words and have mapped those words to the tools2 we use –

Tell me and I Forget, => Talks, Slide-shows, Discussions etc…
Show me and I Remember, => Demos, Screencasts etc…
Involve me and I Learn. => Workshops, Pairing, Tutorials etc…

Workshops provide an environment where people find it enriching, stimulating and take back something with them. So, lets for once call a workshop a Workshop to convey its spirit without hiding or narrowing it by using the word “training”.

References

1. Integral EducationSri Aurobindo Center for Advanced Research (SACAR).
2. The Tao of Transformation – Dhaval Dalal.

Some Scala Code in Sanskrit

Tags

, ,


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?

Exploring Concurrency CodeJugalbandi


This time at Functional Conf 2018, Morten Kromberg, CXO of Dyalog Ltd., Ravindra Jaju and myself presented CodeJugalbandi again. The theme was about exploring concurrency. Conversations between the three artists can be viewed by clicking the links below, or you can simple watch the embedded Youtube video herein.

Melody Name Languages Used Examples
Concurrency and Parallelism Java and APL
  • Concurrency – Echo TCP Server
  • Parallelism – Splitting I/O Task – Portfolio Networth
FP to the Rescue (Etymology of structure of code) Scala, C#, Clojure, APL and JavaScript Gathering Weather and Nearby Places Information
Everything is an Event (Pushing Multiple Values) Reactive Extensions (Java) and Clojure CSP (Core-Async) Portfolio networth using Streaming Stock prices

At the conference, we could demo only first two melodies (see below for the video), The Github Repo has all the melodies mentioned herein.

Slides are simply an index to the melodies.

Note: Further work is in progress on creating other melodies under the theme Exploring Concurrency Codejugalbandi – Mutability, STM and the Actor Model.

Destructuring and Pattern Matching in Functional Programming


Couple of weeks back I presented a introductory session on Destructuring and Pattern Matching at Functional Conference 2018, Bengaluru where I demoed live how Destructuring is different from Pattern Matching by using various Functional Programming languages and other non-FP languages.

Difference Between Destructuring & Pattern Matching

Starting with dynamically typed languages like JavaScript

 
// Destructuring gives us a short-hand way of naming parts of the data-structure.
const list = [1,2,3,4,5,6]
let [first, second, ...rest] = list
console.info("first = ", first);
console.info("second = ", second);
console.info("rest = ", rest);

// Destructuring Object
const name = {first: "Dhaval", last: "Dalal", salutation: 'Mr.'};
const {first: firstName, last: lastName} = name;
console.info(firstName);
console.info(lastName);

// Destructuring Function params
function capitalize({first: firstName, last: lastName}){
  return firstName.toUpperCase() + " " + lastName.toUpperCase();
}
console.info(capitalize(name));

// Destructuring Function params
function distance([x1,y1], [x2,y2]){
  return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}

console.info(distance([0,0], [0,0]))
console.info(distance([3,0], [0,0]))
console.info(distance([0,0], [0,4]))
console.info(distance([3,0], [0,4]))

This is Destructuring. It gives you a short-hand way of naming and getting the innards of the structure. At present (at the time of writing this post), JavaScript does not have Pattern Matching out-of-the-box. So, leaving JavaScript there, I moved to Erlang and then hopped over to statically typed languages like Haskell where I demoed the difference between Destructuring and Pattern Matching.

In Pattern matching, we are not only matching on relative positions of elements in the data-structure, but also trying to dispatch to different definitions (look at the distance function – it has 2 definitions) based on the value inside the data structure. This dispatch is a kind of conditional construct, while in destructuring there is nothing conditional about it.

import Data.Char (toUpper)

data Name = Name { 
  first :: String, 
  last :: String,
  salutation :: String
} deriving (Show)

capitalize :: Name -> String
capitalize (Name fName lName _) = (upper fName) ++ " " ++ (upper lName)
  where
    upper cs = [toUpper c | c  Double -> Double
pythagorean x y = sqrt (square x + square y)
  where
    square n = n ^^ 2

distance :: (Double, Double) -> (Double, Double) -> Double
distance (0,0) (0,0) = 0
distance p1@(x1,y1) p2@(x2,y2)
  | p1 == (0,0) || p2 == (0,0) = (let (x,y) = if p1 == (0,0) then p2 else p1 in pythagorean x y)
  | otherwise = pythagorean (x2 - x1) (y2 - y1)

main :: IO ()
main = do
  let name = Name "Dhaval" "Dalal" "Mr."
  print $ name
  print $ capitalize name
  print $ distance (0,0) (0,0)
  print $ distance (3,0) (0,0)
  print $ distance (0,0) (0,4)
  print $ distance (3,0) (0,4)
  print "DONE"

and finally closing with the same example rendered in Clojure. If this interests you, here is the link for examples in other languages https://github.com/DhavalDalal/destructuring-and-pattern-matching/tree/master/01_languages

Double Dispatch

After that, I demoed the implementation of Double-Dispatch using famous Paper-Scissor-Rock game, starting with Java. The same was then implemented in the above mentioned languages.

; We’ll use record to represent the three choices.
(defrecord Paper [])
(defrecord Scissor [])
(defrecord Rock [])

; Multi-methods can be used to solve this problem
; Here is our dispatch function
(defmulti beats
  (fn [e1 e2] [(class e1) (class e2)]))

(defmethod beats [Paper   Scissor] [e1 e2] "paper loses")
(defmethod beats [Paper   Rock]    [e1 e2] "paper wins")
(defmethod beats [Scissor Paper]   [e1 e2] "scissor wins")
(defmethod beats [Scissor Rock]    [e1 e2] "scissor loses")
(defmethod beats [Rock    Paper]   [e1 e2] "rock loses")
(defmethod beats [Rock    Scissor] [e1 e2] "rock wins")
(defmethod beats :default          [e1 e2] "draw")

(println "paper beats paper = "     (beats (Paper.)   (Paper.)))
(println "paper beats scissor = "   (beats (Paper.)   (Scissor.)))
(println "paper beats rock = "      (beats (Paper.)   (Rock.)))
(println "scissor beats paper = "   (beats (Scissor.) (Paper.)))
(println "scissor beats scissor = " (beats (Scissor.) (Scissor.)))
(println "scissor beats rock = "    (beats (Scissor.) (Rock.)))
(println "rock beats paper = "      (beats (Rock.)    (Paper.)))
(println "rock beats scissor = "    (beats (Rock.)    (Scissor.)))
(println "rock beats rock = "       (beats (Rock.)    (Rock.)))

Below is the link to implementations in Java, Scala, Haskell and Erlang
https://github.com/DhavalDalal/destructuring-and-pattern-matching/tree/master/02_double_dispatch

Subsuming The Visitor Pattern

The session concluded by showing how the (in)famous Visitor Pattern that is usually implemented in languages like Java, C# and C++. Here is the problem statement: How will you enhance this code to include rendering these objects on following platforms?

  • OpenGL
  • SVG

                              +---------------+
	                          |    Shape3d    |
	                          +---------------+
	                          | surfaceArea() |<-------------------------------+
	                          | volume()      |                                |
	                          +---------------+                                |
	                                  ^                                        |
	                                 / \                                       |
	                                  |                                        |
	         +------------------------+-----------------------+                |
	         |                        |                       |                |
	  +---------------+       +---------------+       +---------------+        |
	  |   Cylinder    |       |     Sphere    |       |CompositeShape |        |
	  +---------------+       +---------------+       +---------------+ *      |
	  | surfaceArea() |       | surfaceArea() |       | surfaceArea() |--------+
	  | volume()      |       | volume()      |       | volume()      |
	  +---------------+       +---------------+       +---------------+

Possible Solutions:

  • Solution 1:
    • Introduce renderOpenGL() and renderSVG() methods in Shape3d.
    • We have now made shapes aware of the “drawing platform” specific code. Though they are renderable objects, but how to render would be present inside them.
    • It does not scale to more rendering platforms. We have to add to hierarchy everytime.
  • Solution 2: Use Visitor Pattern
	                      +-----------------+                                    +-----------------+
	                      |     Shape3d     |----------------------------------->|     Visitor     |
	                      +-----------------+                                    +-----------------+
	                      | surfaceArea()   |                                    | visit(Cylinder) |
	                      | volume()        |<-----------------------+           | visit(Sphere)   |
	                      | accept(Visitor) |                        |           +-----------------+   
	                      +-----------------+                        |                    ^    
	                              ^                                  |                   / \
	                             / \                                 |                    |
	                              |                                  |            +--------------------+
	         +--------------------+----------------------+           |            |                    |     
	         |                    |                      |           |   +-----------------+  +-----------------+   
	 +-----------------+  +-----------------+  +-----------------+   |   |  OpenGLVisitor  |  |    SVGVisitor   |   
	 |     Cylinder    |  |      Sphere     |  |  CompositeShape |   |   +-----------------+  +-----------------+   
	 +-----------------+  +-----------------+  +-----------------+ * |   | visit(Cylinder) |  | visit(Cylinder) |   
	 | surfaceArea()   |  | surfaceArea()   |  | surfaceArea()   |---+   | visit(Sphere)   |  | visit(Sphere)   |   
	 | volume()        |  | volume()        |  | volume()        |       +-----------------+  +-----------------+   
	 | accept(Visitor) |  | accept(Visitor) |  | accept(Visitor) |                                               
	 +-----------------+  +-----------------+  +-----------------+ 

Subsumption of this pattern was then demoed in Scala, Haskell, Erlang and Clojure. All these languages provide the facility of Destructuring and Pattern Matching. Below is a Subsumed Visitor implementation in Erlang.

-record (cylinder, {baseRadius = 0, height = 0}).
-record (sphere, {radius = 0}).

volume(#cylinder {baseRadius = BaseRadius, height = Height}) ->
	math:pi() * math:pow(BaseRadius, 2) * Height;
volume(#sphere {radius = Radius}) ->
	4.0 / 3.0 * math:pi() * math:pow(Radius, 3);
volume(List = [_|_]) -> 
  lists:foldl(fun(Shape, Acc) -> Acc + volume(Shape) end, 0, List);
volume([]) -> 0;
volume(_) -> not_ok.

surfaceArea(#cylinder {baseRadius = BaseRadius, height = Height}) ->
  BaseArea = math:pi() * math:pow(BaseRadius, 2),
  BaseCircumference = 2 * math:pi() * BaseRadius,
  2 * BaseArea + BaseCircumference * Height;
surfaceArea(#sphere {radius = Radius}) ->
  4.0 * math:pi() * math:pow(Radius, 2);
surfaceArea(List = [_|_]) -> 
  lists:foldl(fun(Shape, Acc) -> Acc + surfaceArea(Shape) end, 0, List);
surfaceArea([]) -> 0;
surfaceArea(_) -> not_ok.

render(openGL, #cylinder {}) ->
  io:format("~p~n", ["OpenGL: rendering cylinder"]);
render(openGL, #sphere {}) ->
  io:format("~p~n", ["OpenGL: rendering sphere"]);
render(svg, #cylinder {}) ->
  io:format("~p~n", ["SVG: rendering cylinder"]);
render(svg, #sphere {}) ->
  io:format("~p~n", ["SVG: rendering sphere"]);
render(Platform, List = [_|_]) -> 
  io:format("Rendering Composite...~n"),
  lists:foreach(fun(Shape) -> render(Platform, Shape) end, List);
render(_, _) -> not_ok.

main([]) ->
  Cylinder = #cylinder {baseRadius = 10, height = 10},
  Sphere = #sphere {radius = 10},
  Composite = [Cylinder, Sphere],
  io:format("Volume of Cylinder ~p~n", [volume(Cylinder)]),
  io:format("Volume of Sphere ~p~n", [volume(Sphere)]),
  io:format("Volume of Composite ~p~n", [volume(Composite)]),
  % io:format("Volume of 2 ~p~n", [volume(2)]),
  io:format("Surface Area of Cylinder ~p~n", [surfaceArea(Cylinder)]),
  io:format("Surface Area of Sphere ~p~n", [surfaceArea(Sphere)]),
  io:format("Surface Area of Composite ~p~n", [surfaceArea(Composite)]),
  % io:format("Surface Area of 2 ~p~n", [surfaceArea(2)]),
  io:format("~p~n", [render(openGL, Composite)]),
  io:format("~p~n", [render(svg, Composite)]),
  io:format("DONE").

Here is the link to source code https://github.com/DhavalDalal/destructuring-and-pattern-matching/tree/master/03_visitor

Conclusion

  1. Most functional programming languages provide some level of de-structuring. Destructuring gives you a short-hand way of naming and getting the innards of the structure.

  2. The difference between destructuring and pattern matching is that in Pattern matching, we are not only matching on relative positions of elements in the data-structure, but also trying to dispatch to different definitions based on the value inside the data structure. This dispatch is a kind of conditional construct, while in destructuring there is nothing conditional about it. So, Pattern matching is about associating a definition with a particular set of inputs. So, for the same function, we can have many such definitions for inputs that we destructure on.


Note: This is an elaboration of one of the melodies that Ryan Lemmer and myself prepared for the Code Jugalbandi. You can download this Jugalbandi – it appeared in the Healthy Code Magazine in April 2015.

Help yourself by making iTerm2 vivid

Tags


Do you like this vivid iTerm? It shows the host, the time and the current directory, with optional Git branch, all in different colors.

Want one similar to this? Follow the steps below:

  1. Download iTerm themes from https://github.com/mbadolato/iTerm2-Color-Schemes
  2. Go to iTerm2 >> Preferences >> Profiles >> Color Tab. In the Color Tab look for dropdown Color Presets… and select Import… and import the themes.
  3. Choose a theme of your liking
  4. Download Source Code Pro Font from https://github.com/adobe-fonts/source-code-pro
  5. Open the Font Book.app and load these fonts by clicking the ‘+’ button.
  6. Go to iTerm2 >> Preferences >> Profiles >> Text Tab. In the Text Tab, look for Change Font button and change it to Source Code Pro Font.
  7. Finally we can customize the prompt and make it vivid. Go to http://xta.github.io/HalloweenBash/
  8. Play with it, follow the steps and copy-paste the code in your ~/.bash_profile get your prompt customized. Here is how my ~/.bash_profile prompt customization looks like:
    # for iTerm2
    export CLICOLOR=1
    
    function parse_git_branch {
      git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
    }
    
    # prompt
    # format \[\033[COLOR_CODE_HERE\]PROMPT_ESCAPE_OR_TEXT_HERE\[\033[0m\]
    
    export PS1="\[\033[01;35m\]\h \[\033[01;33m\]\t \[\033[01;32m\]\W \[\033[01;34m\]\$(parse_git_branch)\[\033[0m\] \n \[\033[01;37m\]\# => \[\033[0m\]"