Friday, May 9, 2014

Single assignment feature pros and cons

In a programming language if a variable can only be assigned once and another attempt at assignment throws an error, we can say it has a single assignment feature. Prolog and Erlang are two languages with this feature I have used to write substantially involved applications like natural language processing. I believe this feature helps in avoiding errors.

In an earlier post I dealt with the problem of comparison of two equal length strings. Can we write a program for that with the restriction of using only single assignment variables?  Sure we can. Let us have an array of boolean variables. We are left with the problem of summarizing the boolean array.

public static boolean arrbooitercheck(String s1, String s2) {
  boolean [] arrboo = new boolean[s1.length()]; 
  for (int i=0; i < s1.length(); i++){

   arrboo[i]= (s1.charAt(i) == s2.charAt(i));
}

   return summarize(arrboo, s1.length());
                             }

public static boolean summarize(boolean [] arrboo, int length){
 for (int i=0; i < length; i++){ if(!arrboo[i]) return false;}  return true;                                                 }

we return false even if one character comparison is false. If that is the core of the logic of the solution, why do we even need a boolean variable? We can simply write the following.

public static boolean elegantcheck(String s1, String s2) {
   for (int i=0; i < s1.length(); i++){
if(! (s1.charAt(i) == s2.charAt(i))) return false;
      }
   return true;                  }

why are some people reluctant to write this elegant and efficient program?
Returning from the middle of a method though allowed in java, is not used by programmers initially trained in Fortran and  pascal. Recall the student was trying to code his logic into Pascal.

Thinking in terms of necessary and sufficient conditions is acquired in school math concerned with geometry. That helps in computing too.


No comments:

Post a Comment