Daniel Hinojosa's complete blog can be found at: http://www.evolutionnext.com/blog

Items:   1 to 5 of 6   Next »

Sunday, March 20, 2011

Views can be difficult to understand. It is presented at times in a way that can make it even more difficult to understand. In creating a Scala Koan , I decided to make a koan that makes it easy to grok what a view is all about.

In this example, I create list of Ints 1 through 6 and call it lst. lst has two maps. A map takes a function and invokes that function on each element of a collection.

The first map in my example will print out in stdout what will actually be doubled and then doubles that element. The second map will print that it is adding 1 to each element then adds 1 to each element.

The results:


scala> val lst = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: Nil
scala> lst.map{x => println("Doubling %s".format(x)); x*2}
          .map{x => println("Adding 1 to %s".format(x)); x + 1}
Doubling 1
Doubling 2
Doubling 3
Doubling 4
Doubling 5
Doubling 6
Adding 1 to 2
Adding 1 to 4
Adding 1 to 6
Adding 1 to 8
Adding 1 to 10
Adding 1 to 12
res1: List[Int] = List(3, 5, 7, 9, 11, 13)

What should become blatantly clear is that doing two maps is inefficient. The first map goes through each of items, and the second map will go through each of the items again.

This is where view comes in. When you use a view you can add compound functions to a collection before invoking those functions in one fell swoop using the method force. In other words, you can set up all the functions you want and when you are ready, force the view to calculate your maps (or other functions that you are using on your collection).

In the following example, I do the same exact thing as I did in the previous example but if you notice I have lst.view.map instead of lst.map I create a view of the list so that I can add some functions before actually invoking them.

What I get as a result is a SeqView Object. Once I have the SeqView object, I can then call force and get the same final result as before, except this time you will notice that how we got there is quite different. This time instead of doubling all the elements, and then adding all the elements, we interweaved our operations for efficiency, and the list was iterated once instead of twice.


scala> lst.view.map{x => println("Doubling %s".format(x)); x*2}
               .map{x => println("Adding 1 to %s".format(x)); x + 1}
res2: scala.collection.SeqView[Int,Seq[_]] = SeqViewMM(...)

scala>res2.force                                                                                                  
Doubling 1
Adding 1 to 2
Doubling 2
Adding 1 to 4
Doubling 3
Adding 1 to 6
Doubling 4
Adding 1 to 8
Doubling 5
Adding 1 to 10
Doubling 6
Adding 1 to 12
res3: Seq[Int] = List(3, 5, 7, 9, 11, 13)

Tuesday, February 2, 2010

These were two homework challenges from our Albuquerque Scala Study Group last week. One was an NPR Sunday Puzzle.

Do this in Scala....

  1. Write down the digits from 2 to 7, in order. Add two mathematical symbols to get an expression equaling 2010. What symbols are these? (Figure it out in Scala)
  2. 01/02/2010 was a palindrome date and it was awesome! In Scala, figure out the next dates that will be a palindrome, and give me the results in a Stream[Date].

So if I type:


scala > nextPalindromeDates take 5 print  

It should get the next 5 palindrome dates from the day that you run it.

Here are my solutions, with help from the group of course:

Write down the digits from 2 to 7, in order. Add two mathematical symbols to get an expression equaling 2010. What symbols are these? (Figure it out in Scala)



object Runner {
  def eval(s: String): Int = {
    val pattern = "\\d+".r
    var nums = ((pattern findAllIn s).toList)
    val opPattern = "(\\+|-|\\*|/)".r
    var ops =  "+" :: ((opPattern findAllIn s).toList)
    nums.zip(ops).foldLeft(0) {
      (x, y) =>
        val num = y._1
        val op = y._2
        op match {
          case "+" => x + num.toInt
          case "-" => x - num.toInt
          case "*" => x * num.toInt
          case "/" => x / num.toInt
        }
    }
  }

  def main(args: Array[String]) {
    val list = (2 to 7).toList
    val operators = "+" :: "*" :: "/" :: "-" :: Nil
    (1 to 5).foreach{ x => ((x+1) to 6).foreach{ y =>
        operators.foreach { op1 => operators.foreach { op2 =>
             if (x != y) {
               var formula = (list.slice(0, x) ::: (op1 :: (list.slice(x, y))) ::: (op2 :: (list.takeRight(6 - y)))).mkString
               var total = eval(formula)
               if (total == 2010) println(formula)
             }
        }}}}
  }
}

This was harder than it seemed and required an eval that can parse out a String like "2000*13+12" and evaluate it. My strategy was to peel all the numbers into a nums var and then peel all the operators using regular expression. I then zipped up the numbers with their corresponding operators and folded them up for the result.

Next, in my main method I have 4 loops one is the loop to determine the first space to separate the numbers. The next loop is to determine where to space the next set of numbers. So for example, given that x = 2 and y = 4:


2 3 4 5 6 7

It would separate the 2nd space and the 4th space giving me:


2 3 [        ] 4 5 [       ] 6 7 

It is in these spaces that I will put in operator variants. from the 3rd and 4th loop. op1 and op2 will go through each of the operators and fit them in to determine which of the applicable value will work and give me the result of 2010.

After running this application I get the result:


2345*6/7

The 2nd homework question was: 01/02/2010 was a palindrome date and it was awesome! In Scala, figure out the next dates that will be a palindrome, and give me the results in a Stream[Date].

So if I type:


scala > nextPalindromeDates take 5 print  

It should get the next 5 palindrome dates from the day that you run it.

Here is my solution to this puzzle:


object PalindromeDates  {
  val datesOnlyFormat = new SimpleDateFormat("MMddyyyy")
  val dateFormat = new SimpleDateFormat("MM/dd/yyyy")

  def isPalindrome(cal:Calendar) = {
    val fmt = datesOnlyFormat.format(cal.getTime())
    fmt.reverse.toString == fmt
  }

  def getNextPalindromeDate(cal:Calendar):Stream[Calendar] = {
    cal.add(Calendar.DATE, 1)
    if (isPalindrome(cal)) Stream.cons(cal, getNextPalindromeDate(cal))
    else getNextPalindromeDate(cal)
  }

  def main(args:Array[String]) {
    getNextPalindromeDate(Calendar.getInstance()) take 30 foreach {x=>println(dateFormat.format(x.getTime()))}
  }
}

This solution obviously uses recursion with getNextPalindrome date. It goes through each Calendar. If the calendar is a Palindrome date as determined by isPalindrome, then the date is conssed (New Word!) to the stream and recursed again with the calendar. One thing that stuck out like a sore thumb was the mutable Calendar, given that Scala is a functional language and has a strong culture of having just about everything as immutable as possible with no side effects.

The main method for this application is different that the homework I provided just because I wanted cleaner and sexier output. I also gave it 30 instead of 5 to see if it can handle it and it did, and it did so surprisingly fast. Here is the result...


11/02/2011
02/02/2020
12/02/2021
03/02/2030
04/02/2040
05/02/2050
06/02/2060
07/02/2070
08/02/2080
09/02/2090
10/12/2101
01/12/2110
11/12/2111
02/12/2120
12/12/2121
03/12/2130
04/12/2140
05/12/2150
06/12/2160
07/12/2170
08/12/2180
09/12/2190
10/22/2201
01/22/2210
11/22/2211
02/22/2220
12/22/2221
03/22/2230
04/22/2240
05/22/2250

So try out these puzzles on your own and see how well you can do, and try some other solutions. Better yet, form either a Scala User Group or a Scala Study Group in your area and work on it together.


Tuesday, November 24, 2009

As part of the Scala Study Group in Albuquerque, we had an assignment to reproduce some of the popular design patterns in Scala. Although the assignment is over, it is worth while to log about it. The following pattern was taken from Groovy Decorator Example.


trait Logger {
  def log(message: String) = {
    message
  }
}

Figure 1: Establishing a trait shared by all Loggers.


object StdLogger extends Logger

Figure 2: Objects are explicit creations of an object. There are no statics in Scala, and for good reason. Reasons that are too many for me to cover here. What this does is create an object called StdLogger. This is merely an implementation of the trait with no added behavior.


class TimeStampingLogger(logger: Logger) extends Logger {
  override def log(message: String) = {
    val now = Calendar.getInstance
    now.getTime.toString + ' ' + logger.log(message)
  }
}

Figure 3: The time stamping logger takes a Logger object and decorates with the current time prepended with whatever message is returned from the parent logger.


class UpperLogger(logger: Logger) extends Logger {
  override def log(message: String) = {
    logger.log(message).toUpperCase
  }
}

Figure 4: The UpperLogger will capitalize all letters returned from the parent Logger object.


object DecoratorRunner extends Application {
  override def main(args: Array[String]) {
    val timeStampingLogger = new TimeStampingLogger(StdLogger)
    val upperLogger = new UpperLogger(timeStampingLogger)
    println(upperLogger.log(StdLogger.log("Decorator for the Scala Study Group")))
  }
}

Figure 5: The application runner itself. I instantiate the TimeStampingLogger and the UpperLogger. Note that I do not instantiate the StdLogger because that already is instantiated because it is an object. I chain them together and produce the needed result.


Thursday, February 21, 2008

...and so far so good...
 
Scott Davis' keynote presentation was great!  He covered the whole perspective of differences and similarities between Java and Groovy.  He reviewed all of the numbers on open-source (i.e., number of people using Java and Groovy; number of people using Apache over proprietary web servers; number of open source web frameworks over proprietary ones like Coldfusion; etc.) and the importance of open-source.  Although there were few mentions of Groovy in the keynote, it definitely was inspirational and made me want to invest in the whole idea of open-source and Groovy.
 
While Scott does sound like a digital minister, he doesn't condemn anyone’s choice of programming language or web framework. Scott simply sells you on an option instead of on a dogmatic belief.  The NFJS conference presenters employ a similar tactic, and they practice what they preach.  Currently, I am sitting in on Programming DSLs with Groovy, presented by Venkat Subramaniam, who happens to be quite the programming language polyglot.
 
After this conference, I am going to gather all of the information that I can on Grails and make a post comparing and contrasting Grails and Seam.  These frameworks are built on two separate ideals and I will try to be unbiased and academic in my opinions.  I look forward to writing it.

Monday, February 18, 2008

Here is the presentation of 'Agile Development with JBoss Seam'  that I tried to give at JBoss World 2008 in Orlando Florida.  I use the word 'try' because when I got on stage, I became so excited that I ended up expanding on every topic of every slide.  Then, when the proctor indicated that there were only five minutes left, I started to freak out and sweat buckets - I had only gone through half of what I wanted to present! :(  It was all downhill from there...

Unfortunately, the dry run that I gave to my JUG before-hand didn't help at all, because the atmosphere at JBoss World put me into a 'sharing' mode so that all I wanted to do was dump everything 'Seam' from my wet squishy brain onto the folks that attended my presentation.

So even though the actual presentation didn't go the way I wanted it,  the work I put into it did.

To download the slides (format is OpenDocument Presentation), click here: www.evolutionnext.com/blog/files/jbossworld_presentation.odp

To download the demo seam-gen project, click here:
www.evolutionnext.com/blog/files/jboss_world_2008_download.zip

The download requires a little bit of setup. Don't worry, it isn't anything difficult. ;)  All of the information you need is in the README.txt file (located in the demo seam-gen project zip file).  The demo is licensed as GPLv3 to encompass all of the component's licenses.  

I was thinking of maturing this little project as a reference implementation for testing in Seam.  If anyone out there is interested in having me upkeep this demo, let me know.  One consideration that I need to make is whether to host the demo from here or add it to the Seam project.  I am leaning towards the latter.

Items:   1 to 5 of 6   Next »