Hand-Toss a Lazy Sequence in C#


Idiomatic approach in C# is to use Generators (using yield) that produce an IEnumerable, but once can hand-toss a lazy sequence a.k.a Stream from first principles using Lambda. Here is an implementation.

Advertisements

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\]"
    

How to disable failed discrete-GPU (NVIDIA GeForce GT 650M) for 15″ MacBook-Pro 10,1 (mid-2012) on High Sierra 10.13.4


It all started when my MacBook Pro showed me black screen after waking from sleep. After that, many times I would boot straight into Black Screen, and the only sign that the machine was awake could be just tested by pressing the CAPS LOCK key (turns on the button-light) or connecting an External USB with a indicator light.

I started asking myself why would this happen? Was it due to upgrade to High Sierra 10.13.3 or was it that my machine really developed some hardware problem? I asked a friend of mine what can I do and he suggested SMC Reset followed by PRAM (NVRAM) Reset. I tried all that, but it refused to work. I got my MacBook cleaned and then it booted fine. But as soon as, I started using it, all of a sudden it would show a Black Screen, but CAPS LOCK would still glow green and so I would then reboot it again, only to Black screen. Sometimes, upon restarting the first problem message that I got was GPU panic like the one shown below:

Anonymous UUID:       32BD6DA8-14C2-38AD-E466-F3B6DDCE6F7F

Fri May 18 19:43:24 2018

*** Panic Report ***
panic(cpu 2 caller 0xffffff7f916c29cf): "GPU Panic: mux-regs 4 0 a0 99 0 8 severity 3 WS-ready 1 switch-state 3 IG FBs 1 EG FBs 0:0 power-state 3 3D idle HDA idle : AGC GPU REGISTER RESTORE FAILED : rdar://7254528, VendorID invalid\n"@/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppleGraphicsControl/AppleGraphicsControl-3.18.48/src/AppleMuxControl/kext/GPUPanic.cpp:162
Backtrace (CPU 2), Frame : Return Address
0xffffff81f9073a90 : 0xffffff800e66e166 
0xffffff81f9073ae0 : 0xffffff800e796714 
0xffffff81f9073b20 : 0xffffff800e788a00 
0xffffff81f9073ba0 : 0xffffff800e620180 
0xffffff81f9073bc0 : 0xffffff800e66dbdc 
0xffffff81f9073cf0 : 0xffffff800e66d99c 
0xffffff81f9073d50 : 0xffffff7f916c29cf 
0xffffff81f9073db0 : 0xffffff7f916bf1ae 
0xffffff81f9073df0 : 0xffffff7f916c2443 
0xffffff81f9073e30 : 0xffffff800ec9f71c 
0xffffff81f9073ea0 : 0xffffff800ec9f646 
0xffffff81f9073ed0 : 0xffffff800e6a77e4 
0xffffff81f9073f40 : 0xffffff800e6a7345 
0xffffff81f9073fa0 : 0xffffff800e61f4f7 
      Kernel Extensions in backtrace:
         com.apple.driver.AppleMuxControl(3.18.48)[09DFEF11-0A5B-369B-91C5-FD32B3E62DD3]@0xffffff7f916b4000->0xffffff7f916c6fff
            dependency: com.apple.driver.AppleGraphicsControl(3.18.48)[91D747FB-F341-33F2-BBDD-0CA45A3CC1B2]@0xffffff7f916b1000
            dependency: com.apple.iokit.IOACPIFamily(1.4)[95DA39BB-7C39-3742-A2E5-86C555E21D67]@0xffffff7f8f35a000
            dependency: com.apple.iokit.IOPCIFamily(2.9)[1850E7DA-E707-3027-A3AA-637C80B57219]@0xffffff7f8ef34000
            dependency: com.apple.iokit.IOGraphicsFamily(519.15)[D5F2A20D-CAB0-33B2-91B9-E8755DFC34CB]@0xffffff7f8fdb3000
            dependency: com.apple.AppleGraphicsDeviceControl(3.18.48)[89491182-0B41-3BC3-B16F-D5043425D66F]@0xffffff7f91219000

BSD process name corresponding to current thread: kernel_task
----

So, I started Googling for this GPU Panic problem and found that many laptops had this issue and that many forums said it was all due to a faulty discrete GPU on the logic board. I missed the replacement program (as I was not even aware that it existed until I hit this problem) and now my machine is out of warranty (more than 51/2 years now). The machine is a 15″ MBP 10,1 (mid-2012) with dual GPU system. I thought, if I could get Logic board changed, I should be okay, but in many forums many users who got that done were not still immune from that problem. It had all the possibilities of appearing once more (even after changed GPU). Secondly, Logic board replacement is an expensive affair! Last option, of course, is to get a new MPB, but I wanted to wait till the WWDC June 2018 announcement.

Anyways, I still wanted to make sure that this is indeed the same GPU problem that I was facing. So, I thought may be I should downgrade the OS X to El Capitan or Sierra and rule out my High Sierra upgrade. After checking with both the older OS X, I started getting very frequent GPU panics, like the one pasted above. With laptop in comatose mode 😉 I literally had to resuscitate it using SHIFT + OPT + COMMAND + Power (SMC reset) by counting 10 and then do a CMD+OPT+R+P+POWER (NVRAM Reset) and the wait for sometime and power up again. It all then depended on the spirit to re-enter the machine and bring it to life again :)) Many times, it had barely woken up and slipped into coma again. Then sometimes it would work for 2/3 days straight, until I don’t open up any BIG IDEs like Intellij or any program like Chrome or Firefox that caused a switch to dGPU.

In the Apple forums, I saw people had already disabled the on-board dGPU and they had a working system with only the built-in iGPU. However, it was done for older makes (year 2011) of the MBP. I searched for my particular make with NVIDIA GeForce GT650M Graphics card. I stumbled upon 2 links:

1) https://github.com/mayankk2308/purge-nvda/blob/master/purge-nvda.sh (NVIDIA driver)
2) http://www.javajirawat.com/2018/02/macbook-pro-2012-broken-gpu-work-around.html (AMD driver)

Thanks to them and I combined both their solutions to disable the dGPU on my system.

The Steps:

    I. Sanity Check (find the number of GPUs):

    • You can either go to Apple Menu > About This Mac… > Overview Tab > Press System Report…Under Hardware, look for Graphics/Displays…
    • Or you can type at terminal (and it displays the same information)
      $ system_profiler SPDisplaysDataType 
      
      Built-In GPU (Integrated GPU - iGPU): Intel HD Graphics 4000 1536 MB
         ...
         ...
      Second GPU (Discrete GPU - dGPU): NVIDIA GeForce GT 650M
      gMux Version:	3.2.19 [3.2.8]
         ...
         ...
      Display - Color LCD Resolution - 2880 x 1800 Retina Framebuffer Depth:	24-Bit Color (ARGB8888)
      Metal:	Supported, feature set macOS GPUFamily1 v3
      
  1. II. In Recovery Mode, do the following (Using the Recovery Terminal Utility), do the following:

  2. Boot into Recovery Mode (by holding Command+R while pressing the power button). At terminal prompt, we will disable SIP (System Integrity Protection)
        $ csrutil disable
        System Integrity Protection now disabled.
        
  3. Reboot again in Single User mode.
        $ reboot 
        $ # and then hold Command+S keyboard buttons
        $ # to boot in single user mode.
    
        
  4. III. In Single User Mode, do the following:

  5. Do a Hard disk Check:
     
        $ /sbin/fsck -fy
        $
        
  6. Mount Root file system in Read-Write (uw) mode:
        $ /sbin/mount -uw /
        $
        
  7. Create a backup directory to hold existing GeForce drivers:
        $ mkdir /GeForce_save
        $
        
  8. Move all the GeForce drivers to the backup directory:
        $ mv /System/Library/Extensions/GeForce* /GeForce_save
        $
        
  9. Delete Driver Cache
        $ rm -rf /System/Library/Caches/com.apple.kext.caches/
        $
        
  10. Force refresh of Driver cache:
        $ touch /System/Library/Extensions
        $ kextcache -q -update-volume /
        $
        
  11. Reboot again (into Recovery mode while holding Command+R)
        $ reboot 
    
        
  12. IV. In Recovery Mode, do the following (Using the Recovery Terminal Utility):

  13. Remove Nvda Booting GPU
        $ nvram boot-args="nv_disable=1" 
        # OR append existing boot-args 
        $ nvram boot-args="nv_disable=1 $(nvram boot-args 2>/dev/null | cut -f 2-)"
        $ nvram fa4ce28d-b62f-4c99-9cc3-6815686e30f9:gpu-power-prefs=%01%00%00%00
        $
        
  14. Enable SIP (System Integrity Protection)
        $ csrutil enable
        System Integrity Protection now enabled.
        
  15. Reboot machine in normal mode
        $ reboot
         
        

IMPORTANT NOTE:

  1. By using nvram boot-args=”nv_disable=1″, you will lose brightness control (F1/F2 keys) and sleep mode (clamshell open/close) does not work. When the computer awakes after sleep, it shows a black display. Also, the brightness slider will no longer show up in System Prefs -> Display. However, you can adjust the backlight to a fixed value. For example, I prefer the low backlight-level. In the recovery terminal,
    $ nvram backlight-level="\%00"
    
    

    Various valid values in the increasing order of brightness are: 0%00, C%00, \%00, z%00, %9f%00, %cb%00, %01%01, A%01, %8c%01, %e6%01, P%02, %d2%02, \%03, %ff%03.

  2. Once you use this patch, you won’t be able to connect to external displays and project on that screen (as MacBook-Pro routes to external ports – HDMI and thunderbolt using the dGPU)
  3. When the computer after sleep, it shows a black display but the machine is still running the OS. To get the screen back, I need to turn the machine off. But this means, its improper shutdown when you have processes running. One solution is that you can remote desktop into the system by using Screen Sharing or VNC. Using this you can get back into the machine, and work like usual until the process completes and then shutdown the machine. Also, while using Screen Sharing, you can project the shared screen on an external display from that client machine.

Update: I’ve updated to High Sierra 10.13.6. After this I applied the Security Update 2019-001 and it went fine. I could boot back into my Mac and work with it just like before. I have not updated to Mojave yet. Once I am able to get that done as well, I’ll share my findings on this post. Stay tuned!

Improvised Tasks.tmbundle for TextMate

Tags


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

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

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

Improvised-Todo-With-Skip-Task

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

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

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

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

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

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

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

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

Sri Aurobindo’s Integral Education Principles


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

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

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

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

For details you can refer to the slides below: