My First Scala Program

Posted in Tech on August 3rd, 2009 – Tags:

A while back for my birthday, I got the Odersky Programming in Scala book and today I finally got a chance to crack it and play around. I had been interested in trying to pick up one of the new wave of dynamic JVM langagues like Groovy, JRuby, or Jython and had settled on Scala. I had read a suggestion that Project Euler would make for a fertile playground of test problems to learn on, and having already done the first several in Java that rang true for me. So, here is my overly complicated solution to the simple first problem..

//If we list all the natural numbers below 10 that are multiples of 3

//or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

//Find the sum of all the multiples of 3 or 5 below 1000.

import scala.actors._

object Adder extends Actor {

var sum = 0

def act() = {

react {

case (num: Int) =>

sum += num

act()

case “REPORT” =>

Console.println(“Total = “ + sum);

}

}

}

object ProblemOneRunner {

def main(args: Array[String]): Unit = {

Adder.start

for(i <- 1 to 999) {

if(i % 3 == 0 || i % 5 == 0 ) {

Adder ! i

}

}

Adder ! “REPORT”

}

}

It starts out looking something like a Java program with an import statement, although Scala uses the _ notation to import everything instead of * since * is an identifier. Scala supports a lot of flexibility in its import statements, they can show up anywhere and you can use them to remap names or set up exclusion filters – but lets not get to far astray.

Next, you’ll notice that my program has two objects and no classes. Its not that Scala doesn’t have classes, its just that Scala classes don’t have the Java concept of static – if you want a singleton object, you use the object keyword. The solution I have above uses one singleton as the main program entry point and another Adder singleton that extends Actor. This is just so I could play with Scala’s built in multithreading and message passing support – obviously this problem doesn’t really require it but I thought I’d try it out anyway for fun.

The Adder has its own sum variable it uses to keep track of the numbers it will add up – Scala uses the var keyword for variables that can be reset and val for ones that can’t. You’ll notice the lack of any type declaration here, its not that Scala variables are not typed, its just that it uses type inference to figure out what they are. Also, Java users will notice the lack of semicolons – semicolons are optional in Scala in most cases. The Adder overrides the act method, the entry point for threads, and then calls react which will look for a message in the actor’s inbox and if it doesn’t find one, put the actor to sleep. Unlike some of the other constructs Scala provides for Actors like receive, the thread will die at the end of react instead of looping so we have to put a call to act() at the end of the int message we send it to keep it alive.

In the main method, we start up our Actor thread, then loop through 1 through 999 looking for numbers divisible by 3 or 5 to send to our Adder, then once we are done we send a message to the thread to report and finish its loop. Again, Java users will notice the easy condensed for loop and the ! message passing syntax.

I’ve barely scratched the surface of Scala here, I’ll try to get a couple more problems done and posted that likewise abuse language features as I get time.

1 Comment

Cerebral Imprint 2.5

Posted in Projects on June 23rd, 2009 – Tags: ,

Whew! I just finished a major rewrite on my flash card app, Cerebral Imprint. One of the early design decisions I made way, way back when I first wrote the application (ouch, was it really back in 2004?) was to make it a single document application. The application would store all its information about the user’s data in a single file in the user’s Library directory. This was simple, however as time went on and my personal flash card library grew I realized it just wasn’t going to cut it.

The next thing I did was to hack on support for the application to read and write its flash card data to other files. When the application would start up it would prompt the user if they wanted to open an existing file or start a new one. Only one file could be open at a time but it was the least invasive way to get multiple file support without changing a lot of code (and how the user interface works). It worked but I wasn’t really happy.

Thing is, there is way to this the right way. You base your application off NSDocument and Cocoa provides all sorts of functionality for you. It was really bugging me that Cerebral Imprint wasn’t acting like a normal document-based application for the Mac should behave so I decided on perhaps a overly drastic course of action – I started from scratch with a totally fresh NSDocument application and imported code as I needed from my old project. It took a lot of time but ultimately it was worth it since as I imported the old code I took the opportunity to scrub cruft going back in some cases to 2004 that was no longer being used and really clean things up.

I also added some new functionality along the way. For instance, I’ve been playing around with flash cards apps on my iPhone but haven’t felt like tackling writing an iPhone app right now so I’ve added export functionality so I can export my cards into apps like Notecards to tote with me.

Be the first to comment

SIFF 2009

Posted in Life on May 24th, 2009 – Tags:

It’s that time of year again. Ahh, SIFF – how I love thee so. Last night I was convinced to go to the midnight showing of the campy Norwegian nazi zombie flick, Dead Snow. Perhaps not a film classic, but a nice mix of humor and abundant intestines.

As usual, you can check out the films over on the SIFF site or over at the Stranger guide – nice twist, this year you can download an iPhone app too.

Be the first to comment

Crop Circles

Posted in Random on May 17th, 2009

A friend of mine who for some reason wishes to remain anonymous added his graphics to an amusing crop circle rant that was floating out there on the internet, a synergy that surely hit comedy silver if not gold. Warning: Naughty words are spoken and there may be one or more elements of animated fecal matter.

Be the first to comment

What a Jaunty Macbook you have there…

Posted in Tech on April 28th, 2009 – Tags: ,

I’ve been taking another stab at dualbooting my Macbook1,1 with the release of Ubuntu 9.04. As a mostly-happy Macophile, why dualboot you might ask? A couple of things – a weakness for playing around with Unix operating systems (a bad habit I picked up in college) and freakin Java 1.6. The problem is Apple decided not to release a 32bit version for 1.6 and my Macbook is the older Core Duo version and thus not supported. Now, normal people might sigh and stick to 1.5 or take this as an opportunity to buy a new laptop. The slightly more practical (or cheap) who refuse to give up probably turn to soylatte, the port of BSD to OS X (Metal L&F only – no pretty Mac L&F). I, however, with more disk space than sense, turned to rEFIt to set up a dual OS X/Linux setup.

I won’t detail how to setup a dualboot system, there are enough tutorials out there if one searches for them. When I first setup my laptop I installed ubuntu  8.10 and quickly ran into  two annoyances  – an error message about my keyboard layout and the fact that by default the machine is very hard to use since the touchpad causes the cursor to jump around randomly while typing. Not in a mood to research them at the time, I got distracted and sadly it wasn’t until 9.04 that I tried again. Both these problems persist with Jaunty so if you want to run it on your it on your macbook, you are going to run into them.

The first issue manifests itself as an error message stating “Error activating XKB configuration” everytime you log into X. This is related to xorg not apparently knowing what to do with the macbook keyboard variant – there is an umbrella bug ubuntu uses to capture all these types of errors you can find here. The solution is to modify your xorg.conf file to give X more information however I haven’t dinked around with this yet since its just a minor annoyance.

The issue with the trackpad just about renders the machine unusable for anything but the most simplist tasks however its luckily easy to fix (or at least mitigate). In Jaunty, just add a startup application that looks like this:

syndaemon -d

This will start up a program in the background every time you login that will disable the trackpad while you type, preventing it from causing the cursor to jump all over the screen. Syndaemon has a couple more options you can play with such as how long to disable the trackpad for but so far I’m finding the default settings to work ok.

A couple more random hints:

  • If you upgraded Jaunty and are now having problems with flash sites like Hulu telling you need flash 9 when you _know_ you had flash installed, try using synaptic to complete remove and then reinstall the flash-installer package – thats what it took for me  to get it working again on my living room media box.
  • If you are a quicksilver addict, check out Gnome Do – very slick and the keyboard shortcuts are even the same by default.
Be the first to comment

JavaBat

Posted in Tech on March 27th, 2009 – Tags:

Stumbled over another Java practice problem site for those poor bored individuals who just like writing code. This one is unique in that you are basically asked to implement a function which matches some specification you then write in a web form. On submit the site compiles the code and runs some unit tests against it to verify you have solved the particular challenge. You can create an account to track your progress if you like but its not mandatory. Pretty cool.

JavaBat

Be the first to comment

Cerebral Imprint 2.0.1

Posted in Projects on December 31st, 2008 – Tags: ,

I’ve been working a lot on my flashcard application behind the scenes lately doing things like switching over to cocoa bindings, messing around with UI, adding little features here and there. I went through a drawer phase for a while but thankfully regained my senses and ripped them all out.

I went ahead and cleaned up the code enough that I’m not *totally* embarssed for other people to check it out so I added a page dedicated to the application as part of my wordpress site and added the source code to a free subversion hosting service (www.assembla.com).

Be the first to comment

Maui, part 3

Posted in Travel on December 14th, 2008 – Tags:

Well, I’m not sure what is up with weather forecasting for the Maui area, but pretty much the only trend I can extract is that when they call for rain all day, its going to be gorgeous and 90+ degrees while if they call for a slight chance of rain, that means downpours for sure.

How have we been keeping ourselves entertained you might ask?

  • Went and checked out the sharks, turtles, and other fish at the Maui Ocean Center . They also put on a bit of a show where they put a diver into a big old tank to feed the fish and allow you to do a bit of a Q&A with the marine biologists.
  • Drove though Kihei down south to check out the lava fields and do a bit of snorkeling, ended up doubling back and spending the afternoon at the delightful Big Beach .
  • Saw a fantastic magic show over at Warren & Annabelle’s .
  • Went on an nice day hike up the Waile’e Valley, along a river and over a couple of suspension bridges, up to a waterfall. Apparently Lost filmed some scenes up here.
  • Had a late lunch in Paia and ended up spending the afternoon at the Paia Bay Beach .

After seeing the weather reports from back home I am *not* looking forward to going home tomorrow.

Picture on Flickr as usual.

Be the first to comment

Maui, part 2

Posted in Travel on December 11th, 2008 – Tags:

What did we wake up to this morning?

Yep, total downpour, pretty much all day long. O’ahu took the brunt of the storm, getting 14(!) inches of rain in less than 24 hours. Maui didn’t get it as bad, but it got a whole bunch of rain. The 5 day forecast isn’t looking too hot either – laugh it up all you haters, bitter that I’m in Hawaii and you’re not :P . We’re not letting it hold us back though. Today we took the drive out to Hana anyways and we have more plans for the rest of the time here. Yesterday was actually really nice, perfect to drive up to over 10,000 ft and check out Haleakala.

More photos over on flickr.

Even more over on Jason’s Blog.

Be the first to comment

Maui

Posted in Travel on December 10th, 2008 – Tags:

Spending a week in Kahana with my parents, my 3 younger brothers, and my younger brother’s family. Its my first time to hawaii, what are my quick first impressions?

  • I’ll take 80-85 degree weather over 30-40 degree weather anyday, cloudy or not.
  • Things in Maui are pricey – gas is about $1 more a gallon than back home, food ranges from slightly to extremely more expensive.
  • Some areas of Hawaii remind me of pictures I’ve seen of the moon, or ones sent back by the Mars lander, others remind me more of eastern washington. I’ve only seen a bit of land so far that reminds me of Jurassic Park
  • Walking through Lahaina, most of it seems really touristy. I’ve never seen so many people trying to sell you time shares clustered together in like a 5 block radius before.
  • Little kids like to get up early. really early.

Bored? First round of photos can be found here.

1 Comment