Archive for the ‘tech’ Category
Procedural vs. Functional
With the rise of Scala and Clojure, there’s been a lot of talk lately about procedural vs. functional styles of coding. Most developers are accustomed to procedural coding, and functional can be hard to get a handle on. I was working through Programming in Scala (again) this morning, and I came upon this function:
// Procedural implementation
def longestWord(words: Array[String]) = {
var word = words(0)
var idx = 0
for (i <- 1 until words.length)
if (words(i).length > word.length) {
word = words(i)
idx = i
}
(word, idx)
}
The purpose of this function is to find the longest word in the passed-in array, and return a tuple with that longest word, and its index in the array. You can see that in this function, we have two vars, one for the current longest word, and another for its index in the array. We then use a for expression to walk the array, reassigning word and idx when we find a longer word. This is very much like how you would write this in Java.
I decided to rewrite this function in a more functional style, just to see how my functional chops are coming along. Here’s what I ended up with:
// A more functional implementation
def longestWord(words: Array[String]) =
(("", -1) /: words.zipWithIndex) {(old, cur) =>
if (cur._1.length > old._1 .length) cur
else old
}
First of all, notice how much shorter this function is than the first one. Also, notice that there is only a single expression in the function, so the outer curly braces aren’t necessary. What this expression is doing is calling zipWithIndex on the passed-in array, which results in an array of tuples containing each word and its index. We then call foldLeft using its operator name of /:, with its initial argument being a tuple with an empty string and -1 for an index. What foldLeft does is apply the function value passed to it to pairs of arguments. On the first pass, the arguments are what was passed in and the first element in the array. On the second iteration, the arguments are the result of the first pass and the second element in the array. This then continues through the entire array. What is returned after the final pass will be a tuple that contains the longest word in the array, and its index.
Now, I don’t claim to be a functional master or anything, but I think this is a decent illustration of how the functional style can reduce the lines of code, and the number of mutable variables, while making the code easier to read and understand.
Slides From My Presentation on Operator Overloading In Scala
Last night I spoke at the Atlanta Scala Enthusiats meeting about operator overloading and a little on implicit conversions. I think the talk went well as I got lots of really good questions from the audience, and they laughed at my jokes. This presentation grew out of a blog post I wrote a few months ago entitled Scala Gets Operator Overloading Right; I beefed it up and made some slides and more code samples. Incidentally, if you Google for “scala operator overloading” that blog post is the first result.
For those of you who weren’t there, here are my slides and the code samples that go with them. I wrote these samples against Scala 2.7.7.final. They should work with the latest Scala 2.8, but I haven’t verified this.
And here’s the source code: oopres.zip
What the Heck Is a Tuple, Anyway?
Yesterday I was talking with a friend about Scala and the subject of tuples came up. We both had a bit of a laugh that neither of us was sure how to pronounce it, though we both leaned toward TUH-ple instead of TOO-ple. Anyway, the utility of tuples in Scala was not immediately apparent to him, so I thought I’d take a whack at explaining it here.
A Tuple in Scala is an immutable container used for storing two or more objects, possibly of different types. While a List or Array can only store objects that all have the same type, Tuples can store objects of any type. The most common use of tuples is when you have a method that needs to return more than one value, but creating a class for that return value is more trouble than it’s worth. It’s true that for same-type objects you could return a List, and for different-type objects you could return a List[Any], but both of these have downsides, which we’ll discuss.
Let’s look at a very contrived example. Let’s say you created a function that takes a string and returns the starting index of the first numbers if finds and the numbers themselves. That code might look like this
def reFind(str: String) = {
val re = """(\d+)""".r
val m = re findFirstMatchIn str
m match {
case Some(m) => (m.start, str.substring(m.start, m.end))
case None => (0, "")
}
}
(I’ve removed any error checking for brevity.) You can see here that we’re creating a regular expression that looks for one or more numbers grouped together. We then match that against the passed-in string. The matching method returns a Some[Match], so we pattern match against that to see if we actually got a match. If we did, we create a tuple with the starting index of the match, and the match itself, and return it. If not, we return a tuple with 0 for the starting index and an empty string.
Calling this function looks like this
scala> val t = reFind("foo 123 bar")
t: (Int, java.lang.String) = (4,123)
You can see that what was returned is something with type (Int, java.lang.String); that’s actually an instance of Scala’s Tuple2 class. (There’s a synonym for Tuple2, called Pair.)
Now that we have this tuple, what do we do with it? If you want to access the values it contains, you do it in a way that might seem a bit strange at first. To get at the elements, you could do this
scala> val i = t._1 i: Int = 4 scala> val m = t._2 m: java.lang.String = 123
There are two things to point out here. First, unlike Lists and Arrays, you don’t use the () notation. You use a method consisting of an underscore and the index of the part you want. Second, unlike Lists and Arrays, tuples are 1-based instead of 0-based. (According to Programming In Scala, this is a nod to Haskell and ML.) Also notice the types of the vals you are assigning. That’s one of the benefits of using a Tuple instead of something like List[Any]; you still get compile-time type safety. Had you instead written the function like this
def reFind(str: String) = {
val re = """(\d+)""".r
val m = re findFirstMatchIn str
m match {
case Some(m) => List[Any](m.start, str.substring(m.start, m.end))
case None => List[Any](0, "")
}
}
and called it, look what happens when you try to store the Int index in a local variable
scala> val l = reFind("foo 123 bar")
l: List[Any] = List(4, 123)
scala> val i: Int = l(0)
<console>:10: error: type mismatch;
found : Any
required: Int
val i: Int = l(0)
^
You would get a similar error trying to assign the String element to a local String val. That’s the major downside to using a List[Any]. (In the first example I used Scala’s type inference to set the types of the local variables; this time I wanted to be explicit to show the failure.)
As I mentioned earlier, you could define a class just to handle the return values of this function. There is nothing wrong with that solution, and some will find it superior to using a tuple, because you can assign meaningful names to the elements. You could define it like this
class ReResult(val index: Int, val part: String)
def reFind(str: String) = {
val re = """(\d+)""".r
val m = re findFirstMatchIn str
m match {
case Some(m) => new ReResult(m.start, str.substring(m.start, m.end))
case None => new ReResult(0, "")
}
}
and call it like this
scala> val l = reFind("foo 123 bar")
l: ReResult = ReResult@57c52e72
scala> val i: Int = l.index
i: Int = 4
scala> val m: String = l.part
m: String = 123
If you think this is more maintainable, then by all means, use it. If you just want to easily return more than one value from a function, then consider using a tuple.
Another point on tuples is that you can assign all the elements of a tuple to local variables in a single step, rather than using multiple calls. So this is equivalent to all the assignments from the earlier examples
scala> val (i: Int, m: String) = l i: Int = 4 m: String = 123
Depending on what you’re doing, this could be a useful way to get at the elements.
And one more thing. There are tuple classes that range from two elements all the way up to twenty-two. The classes are named Tuple2, Tuple3 … Tuple22. The () notation for creating tuples applies all the way up to twenty-two arguments, so you rarely need to actually use the class names. For example,
scala> val t = (23, "foo", 18.0)
t: (Int, java.lang.String, Double) = (23,foo,18.0)
scala> t.getClass
res31: java.lang.Class[_] = class scala.Tuple3
scala> val t1 = ('a', "quick", 23, "year-old", """foxy""".r, List(1, 2, 3))
t1: (Char, java.lang.String, Int, java.lang.String, scala.util.matching.Regex, List[Int]) = (a,quick,23,year-old,foxy,List(1, 2, 3))
scala> t1.getClass
res32: java.lang.Class[_] = class scala.Tuple6
I’m not going to provide an example of creating a Tuple22; that is left as an exercise. :-) I would argue that if you need more than three elements, you really should define a class to hold them. I think that beyond three elements it gets difficult to keep them straight. Tuples are great for holding two or three pieces of information, but don’t go crazy with them.
MiddleClickClose: New Home!
For those of you who have been pining for a working 64-bit version of MiddleClickClose, your patience is about to be rewarded. A fellow called Tom has taken the MCC code, gotten it working with 64-bit Safari and has moved it to its new home. I am no longer maintaining the code, since I don’t use Safari, so from now on, here’s where you should go for MCC:
github.com/Kabal/MiddleClickClose
There you will find all the source code so you can see how it works, or make changes yourself. If you are only interested in using it, you can get a binary bundle here. I haven’t tried it, but Tom assures me that it works. :-)
Thanks Tom-of-no-last-name for taking over the code.
2 Solutions To Project Euler Problem #1
In an effort to not go a whole month without blogging, and in the interest of posting some code samples, I give you two solutions to Project Euler: Problem #1. If you’ve never heard of it, Project Euler (pronounced “oiler” after the Swiss mathematician Leonhard Paul Euler) is a set of increasingly difficult programming challenges. Participants can write their programs in any language and the only goal is to solve the problems and learn something. There are no prizes and you don’t have to show your work.
I had looked at this project years ago, and I swear I thought I had already solved some of them, but maybe I only thought about doing it. Anyway, I have two solutions to the first problem; one in Groovy and the other in Scala. Here, then, is how Project Euler describes the 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.
So, the goal is to take a series of numbers from 0 to 1000, exclusive, find all the numbers divisible by 3 or 5 and add them together. Here’s the Groovy solution.
def subList = (0..<1000).findAll {it % 3 == 0 || it % 5 == 0}
def sum = subList.inject(0) {i, sum -> sum + i}
println "Sum = ${sum}"
This is a very simple program, and I could have written it as a one-line program. I broke it up into a few lines for clarity. As you can see, the first line creates an exclusive range from 0 to 1000. It then calls the findAll method on that range, passing in a closure that will return true if the passed-in digit from the range, called “it” here, is evenly divisible by 3 or 5. The result of findAll is another collection, containing only those values that passed the divisibility test. We then take that list, passing 0 into the inject method, which will neatly sum the values up and return that value. Easy peasy.
Now here’s the Scala version. You’ll notice it is very similar to the Groovy solution.
val subList = for {
i <- List.range(0, 1000)
if i % 3 == 0 || i % 5 == 0
} yield i
val sum = subList.foldLeft(0) {(i, j) => i + j}
println("Sum = " + sum)
I used a sequence comprehension to generate the sublist here. The bit beginning with “for” generates an exclusive range from 0 to 1000, which is then iterated over, assigning each value to “i”. Then, if it is divisible by 3 or 5, it is yielded up by the comprehension. The result is a collection of just those numbers that we want, assigned to the val called subList. We then call foldLeft on that sublist, doing exactly what we did in the Groovy solution. Again, pretty simple.
Now, I could have solved this one in an almost identical fashion to the Groovy solution by using the filter method of lists, but I wanted to solve it first using a list comprehension. Here is the second solution
val subList = List.range(0, 1000) filter {i => i % 3 == 0 || i % 5 == 0}
val sum = subList.foldLeft(0) {(i, j) => i + j}
println("Sum = " + sum)
I timed the solutions and all three finished in just over a second. The second Scala solution seemed ever-so-slightly faster than the other two.
As I get time, I will work on additional problems from the site and post the answers here. I don’t know that I’ll always do solutions in two languages, but I might.
iPhone Interface For My Blog
09/28/2009 Update: Now added a link to the view from Android.
Last week I learned about WPTouch, which is a plugin for WordPress that reformats the theme for the iPhone, Android and other mobile devices. It was an easy install, and I am now happy to report that if you view my blog on a mobile device, you’ll see the new UI. Here’s what it looks like on an iPhone
If anybody has an Android phone, or some other supported mobile device, send me a screenshot so I can see what it looks like.
Thanks to Steve Ziegler, here’s what it looks like from an Android device. Thanks, Steve!
I’m Liking Scala’s XML Literals
How many times have you written a class that you needed to save and restore to/from XML? How did you do it? There are libraries that will do this for you, but I don’t know if any of them have taken the lead. Usually, you have to either have external XML templates that will be filled in, or you have to create the XML through code using DOM or JDOM or some other DOM. I think Scala has a better way.
Enter Scala’s XML literals. In Scala, you can embed XML right in the middle of regular Scala code. For example,
val num = 23 val xml = <person> <name>Tom</name> </person> println(num) println(xml)
In this code, we assign to the val called num the Int value of 23. We then assign the xml val an XML Node, that begins with “person”. That’s neat, but not terribly useful. Here’s where it gets really interesting.
import scala.xml.{Node, XML}
class Person(val id: Int,
val firstName: String,
val lastName: String,
val title: String) {
override def toString = {
id + ", " + firstName + " " + lastName + ": " + title
}
def toXML = {
<person>
<id>{id}</id>
<firstName>{firstName}</firstName>
<lastName>{lastName}</lastName>
<title>{title}</title>
</person>
}
}
object Person {
def fromXML(node: Node): Person = {
new Person(
(node \ "id").text.toInt,
(node \ "firstName").text,
(node \ "lastName").text,
(node \ "title").text
)
}
}
val p = new Person(23, "Tom", "Servo", "Robot")
println(p)
val xml = p.toXML
println(xml)
XML.saveFull("Person.xml", xml, "UTF-8", true, null)
val xmlFromFile = XML.loadFile("Person.xml")
val p1 = Person.fromXML(xmlFromFile)
println(p1)
That’s a longer example, but there’s a lot of interesting stuff in there. Lines 3 – 20 are defining a Scala class, but look at lines 12 – 19. Those lines define a method called toXML that returns the current instance of the class, serialized to XML. I’ve defined the XML structure that I want, and Scala will fill in the values by replacing the stuff between the curly braces with whatever those expressions evaluate to. In this case, it’s just the instance variables, but it could be anything you want, including more XML. So if you have a more complex data structure, it could call the toXML method on its instance variables, and they could handle their own serialization, which would then be placed where it should be in the parent XML document. Nifty, eh?
Now, look at lines 22 – 31. This bit of code is defining a companion object to the Person class, which defines a method to deserialize XML into an instance of class Person. Strictly speaking, I didn’t have to use a companion object; I could have just defined the fromXML method at the top level, but I think this makes the code cleaner. What this method does is take an XML node, tear it apart, and return an instance of class Person, with its instance variables populated.
Lines 33 – 45 exercise this code. The result of running this example look like this
box:~/tmp> scala person.scala 23, Tom Servo: Robot <person> <id>23</id> <firstName>Tom</firstName> <lastName>Servo</lastName> <title>Robot</title> </person> 23, Tom Servo: Robot box:~/tmp>
Pretty neat, eh? In the exercise code, we created a Person object, printed it out, serialized it to XML, printed that out, then saved the XML to a file. We then read that file back in, and deserialized it into another instance of class Person. Using XML literals for de/serialization is a nice application. I can see using this quite a lot. I like how it keeps the XML format right there with the code it will represent, so that when you change the code, you’ll remember to change the XML, too.
Bogus Search Results From Sys-Con
Updated! Be sure to scroll down for the latest!
I’m writing a blog post dealing with Scala’s XML literal syntax and how to use it for object de/serialization and so I wanted to get a list of existing Java XML de/serialization libraries. I went to Google and searched for “java xml serialization” and here’s the first result that I got
Notice the date, which is April 23, 2009. That is, ostensibly, the publication date of the article, right? Now check what happens when you click the link and go to read the article
Again, notice the date. It’s six years ago! So, where did Google get the 2009 date? That’s the date of the latest comment on the article. I’m not sure how they are getting Google to display the latest comment date in such a way that it looks like the publication date, but it looks like they are. I can’t imagine that Google just picked that date from the article when it spidered the site. Am I reading too much into this, or is Sys-Con gaming Google for better placement?
09/24/2009 4:26PM Update: Just for grins, I did my Google search for “java xml serialization” again. The Sys-Con article is still the top hit, but notice what’s missing from the search result
Notice, that there is no longer a date showing. Very interesting.
Scala’s Nice Regex Class
I’m a big fan of regular expressions, because they let you parse text in very concise, and sometimes complicated, ways. Though I agree with jwz about regular expressions in lots of cases, I still use them frequently. Perl was the first language that really let me use regex, way back in 1991. After that I used various implementations in C, Python, Ruby, Java and various other languages. While I was glad that Java 5 finally added regex support, I was disappointed at the implementation. It’s kind of clunky, and because Java doesn’t have regex syntax baked into the language, and no support for “raw” strings, you end up with a regex with twice as many backslashes as necessary.
Last night while reading Programming In Scala, I came upon the discussion of Scala’s regex class. Scala has a raw string, so you have exactly as many backslashes in your pattern as necessary, but each regex you create also defines a Scala extractor, so you can easily bind local variables to groups within the expression.
First, let’s look at the Java code.
Pattern emailParser = Pattern.compile("([\\w\\d\\-\\_]+)(\\+\\d+)?@([\\w\\d\\-\\.]+)");
String s = "zippy@scalaisgreat.com";
Matcher m = emailParser.matcher(s);
if (m.matches())
{
String name = m.group(1);
String num = m.group(2);
String domain = m.group(3);
System.out.printf("Name: [%s], Num: [%s], Domain: [%s]\n", name, num, domain);
}
That’s pretty simple, though the double-backslashes really annoy me. Running this code results in the local variables name and domain getting assigned parts of the email address. The variable called num is assigned null, because the email address didn’t contain a plus sign followed by a number. Now, here’s the same program in Scala.
val EmailParser = """([\w\d\-\_]+)(\+\d+)?@([\w\d\-\.]+)""".r
val s = "zippy@scalaisgreat.com"
val EmailParser(name, num, domain) = s
printf("Name: %s, Domain: %s\n", name, domain)
In line 1, we are calling the “r” method on a raw string. This method converts the String into a Regex and returns it. We’re then assigning it to a local val called EmailParser. Also notice line 5. In that one line, we are declaring three local vals and assigning them whatever the groups in the regex matched, or null if they didn’t match. Just like with the Java example, num will be null since there was no plus sign followed by a number. If you change the email address in either example to something like “zippy+23@scalaisgreat.com”, then all three variables will be assigned parts of the string.
Do you have to have this level of support to do regex? No. Does it make things a lot nicer? Indeed.
Now, I just discovered that in Scala if the regex doesn’t match at all, then a MatchError is thrown. That’s sort of a bummer, because it means you’ll have to add a try/catch around your code. Still, I like the extractor syntax that binds regex groups to local variables in one step.
You can see some more examples of regex in Scala over here.
Announcing JUnitLaunchFixer Eclipse Plugin
My friend Chris and I both work for the same company. Our product has around 900 JUnit tests, and for some of them, the default heap size that Eclipse runs JUnit tests with has become too small. You can change the heap size on individual JUnit launchers, but if you have lots of tests, this gets tedious. It also means that you have to run a test, see if it runs out of heap, change the setting and then rerun the test. We both thought there had to be a better way.
We were wrong. There is apparently no way within Eclipse to set a default heap size for JUnit launchers, which means you have to set them individually. We don’t like that.
Thus, JUnitLaunchFixer was born. This is an Eclipse plugin that will set the max heap size on a JUnit launcher when it is created to a value you have previously specified in the plugin preferences. The default is 1G, but you can tailor it to whatever you want. The first time you start Eclipse after installing the plugin, you will be presented with a selectable list of launchers that you can update, and a chance to set the default heap size. You can select as many or as few as you want. This will only be run once, unless you ask for it to run again by setting a preference.
JUnitLaunchFixer is released under the Eclipse Public License. It’s an open source project, so if there’s something you’d like to see it do, or you want to help out, let us know.
As of this moment, it’s only been tested with Eclipse Ganymede (3.4) on Windows 7 and Snow Leopard. I will be testing with Europa and Galileo soon.
You can download the source and build it yourself, but we also have an Eclipse update site to easily install it from http://junitlaunchfixer.googlecode.com/svn/trunk/JUnitLaunchFixer-update-site/
MiddleClickClose Will Work With Snow Leopard But…
12/02/2009 Update: MiddleClickClose has been updated for 64-bit Safari. More info here.
I have upgraded my Mac to Snow Leopard, and as soon as I loaded Safari, I could see that MiddleClickClose was no longer working. I had already heard from someone that this was so, and I had expected it, so this was no surprise. It is possible to get it working again by right-clicking (or whatever the native OSX clicks are to get the context menu) on the Safari program in /Applications, selecting Get Info, and then checking the “Open in 32-bit mode” checkbox. Once you do that, SIMBL and MiddleClickClose both load, and the plugin works. But you’re in 32-bit mode.
MiddleClickClose is totally dependent on SIMBL. If SIMBL won’t load, neither will MiddleClickClose. The solution is, most likely, to get a 64-bit build of SIMBL, but I don’t know if that’s a simple matter or not. The SIMBL developer has said that he only has a PPC machine running Tiger, so I don’t really see how he’s going to get it running. If he does, then maybe there is hope. If not, your only option is to run Safari in 32-bit mode.
Or use Firefox, which is what I do.
1 eeePC, 2 SDDs, 1 Pendrive, Ubuntu, Win7 and dd – Hoo-wee!
If you’ve ever been here before, you know that I bought an Asus eeePC 900a a few months ago. After buying it, I pulled out the 1G RAM and 4G SDD and replace them with 2G RAM and a 32G SDD. I also swapped a few times between Easy Peasy and Ubuntu Netbook Remix, but I finally settled on the RC of Windows 7. At first, Win7 seemed to be snappy, but as I really used it, it was dog slow. After running some speed tests on the SDD, I discovered that it was pitifully slow, especially when writing, and that was making the system almost useless. I would open Firefox and try to use Gmail, and it would sometimes take over a minute to open an email, meanwhile the drive light was solid, instead of just flickering.
So I took a chance and ordered what looked like a much faster SDD. It shipped on Thursday evening and, much to my surprise, arrived in my mailbox on Saturday. For comparison, the first SSD I bought had these specs:
- Sequential Read: up to 40MB/s
- Sequential Write: up to 15MB/s
By contrast, the new one has these specs:
- Sequential Read: 155MB/sec
- Sequential Write: 100MB/sec
You can see a marked difference between the two. When I bought the first one, I didn’t have anything to compare it to, so it didn’t seem like it would be that bad. It was. Now, these numbers are somewhat deceptive in that they are most likely burst rates, not sustained. So while the new drive is capable of hitting 100MB/sec writing, that’s only for short bursts, and won’t hold out over a long series of writes. It’s sort of like a cheetah; it can run extremely fast, but only for short periods of time.
I decided to install it last night, but since I had already installed Windows 7 on the existing drive, I really didn’t want to have to reinstall it, plus reinstall all my programs and reset all my preferences. So I got to thinking, and I came up with a be-you-tee-ful plan. Let me ‘splain.
I have an 8G pendrive that already had the live image of Ubuntu Netbook Remix on it, and I knew that it was bootable. I booted off that drive and mounted the Windows 7 SSD to see how much space it was using and make a copy. Since there wasn’t enough space on the pendrive for a 32G image, I knew that I would need external storage. I brought it up to my office and then got a MacGyvered external drive enclosure and a spare 160G hard drive working with the eeePC. (I say it’s MacGyvered because a few months ago I tore the enclosure apart, removing the existing hard drive to try to turn it into an external CD-ROM drive. That didn’t work, so when I was doing this operation, the drive was sitting on top of part of the enclosure, upside-down, with the cables hanging out. It was ugly.) I then mounted the 160G drive while booted into Ubuntu from the pendrive, and executed the following command:
dd if=/dev/sda of=eee.iso
For those of you who don’t know Unix commands, dd is a program for doing low-level copies. This command did a full bit-level copy of the entire slow SSD, including all partitions and data, and stored them in a 32G file called eee.iso. (Yes, it’s not really an ISO, but I had to call it something.) That took about 30 minutes to copy the whole drive. I then shut the computer down, replaced the slow SSD with the faster one, and rebooted off the pendrive again. Once it was booted, I remounted the external drive, cd’d into the location where I had put the eee.iso file, and executed this command
dd if=eee.iso of=/dev/sda
About an hour and half later, I had a perfect copy of my original SSD that was bootable, and which Windows 7 was happy with (it even installed the correct driver upon first boot).
I am immensely happy with my system now. It’s extremely fast, and not just compared to what it was. Win7 is snappy and responsive, my programs all work, and I didn’t have to reinstall anything.
And that’s just cool.
The iPhone 3GS GPS Is Crazy Good
I have a Garmin eTrex Venture hand-held GPS that I bought about five years ago. I used it for years mounted to my bicycle handlebars for when I would go trail riding to inject a bit of geekery into my rides. I would then download the tracks off of it and pull them into Google Earth to see where I’d been. It worked pretty well, but it had some annoying tendencies. The first was that it took nearly 10 minutes after turning it on before it really knew where it was. It wanted to get strong signals from twelve satellites before it would give you a decent reckoning of where you were on the planet, and that took a while. It was also very sensitive to cloud cover or tree cover. There were many times I’d be riding through the woods and would be in a particularly dense area and it would completely lose any idea of where we were, which is really not what you want your GPS to do.
Last Sunday I decided to get the bike out after a nearly two-year hiatus and go out to my favorite riding spot, Tribble Mill Park. Before I left, I bought an app for my iPhone 3GS from the app store called Trails. When I got to the park and got my bike out and ready, I ran Trails, created a new track entry and started it up. It almost instantly showed me where we were (just like the Google Maps app that is built-in) on the map. I then put the iPhone back into its leather holster, put that inside a canvas saddlebag that hangs under my bicycle seat, and then climbed into the saddle and started riding. I stopped several times along my route to check on it, and not once did it lose the signal. Let me say that again, in a different way: even though the iPhone was encased in leather, ensconced in a canvas bag and under a bicycle seat and my butt, it never lost the GPS signal. It mapped my route perfectly, as can be seen from this screenshot
That’s pretty darn cool, for a phone! The GPS is not the primary purpose of the device, yet it performs far better than a dedicated GPS device. Now, GPS devices in general may be a lot better now than they were five years ago when I bought mine, so this may be an unfair comparison, but it really blew me away. I had thought about getting a handlebar mount for the iPhone, but if it can do what it needs to do from the relative safety of the saddlebag, I’d much rather keep it in there.
By the way, the Trails app is quite nice and completely worth the $3.99 it cost. I like the fact that you can stop and restart it to pick up where you left off. One really nice feature is that it has a button to launch the iPhone’s camera, so you can take pictures along the way without exiting the program. That’s a nice touch. It also requires you to name each track, which are kept in separate “files” so one track doesn’t show up overlaying another on the map. If you’re into trail riding and you have an iPhone 3GS or 3G, consider buying this great app.
MiddleClickClose Updated For Future Safari Versions
08/31/2009 Update: For Snow Leopard compatibility, see here.
Yesterday Apple release Safari 4.0.3 which, of course, broke MiddleClickClose. Again. The problem lies in the file Info.plist that is part of the plugin. From what I read about SIMBL, good practices said that you should include a key called MaxBundleVersion whose value was the internal version number of the app you were patching. The problem is that every time Safari gets updated, Apple increments that number and SIMBL won’t load the extension any more, since it proclaims that the maximum version of Safari it should be loaded with is the previous version.
I usually play catch-up with Apple and get MiddleClickClose updated a day or two after a new Safari ships. I’ve decided to stop that and have removed the MaxBundleVersion from the Info.plist. This is, after all, a dirty hack, so why not make it even hackier?
If you re-download and re-install, you shouldn’t ever need to update it again. If you already have it installed, you can just edit the Info.plist file that will be in ~/Library/Application Support/SIMBL/Plugins/MiddleClickClose.bundle/Contents, removing the two lines that look like this
<key>MaxBundleVersion</key> <string>5530.18</string>
Here are the new downloads
- Binary – MiddleClickClose.zip
- Source – MiddleClickClose-Src.zip
Scala Limerick
On the Java Posse mailing list, there’s a message thread consisting of limericks about Scala or other languages. While I don’t claim to be a poet, here’s my submission
There once was a lang called Scala
That was sweeter than juice from Odwalla
Whether foldLeft or foldRight
It it such a sight
To see Lists reduced down with such might!
I won’t win any prizes for that one, but I thought it was somewhat clever. Of course, ten seconds after posting it, I realized that it’s not a true limerick, because the fifth line is supposed to rhyme with the first two. Oh well. There goes my career as a poet.
MiddleClickClose for Safari 4.0.1
A day or so ago Apple released Safari 4.0.1 and bumped the version number in the process. Safari 4.0 was 5530.17, while Safari 4.0.1 is 5530.18. After installing the update, MiddleClickClose was still loading, even with the minor version mismatch. I don’t know if Safari only looks at the first part of the number when specified in an Info.plist for MaxBundleVersion, but just to be on the safe side, I bumped it to 5530.18 and have re-released it. If it’s working fine for you, don’t bother getting this version. That’s the only change I made.
Apple Doesn’t Seem To Want My Money
Yesterday, like six billion other people, I tried to pre-order a new iPhone 3GS from the Apple Store online. After trying multiple times getting multiple timeouts, I was finally given a message stating that they could not complete my request online, and that I needed to go to a brick-and-mortar Apple Store to complete it. This didn’t completely shock me since when I bought my first generation iPhone, I could not activate it through iTunes, and instead had to visit an AT&T store.
Shortly afterward, I received an email from concierge@apple.com, with this text
Thanks for starting your iPhone purchase online. To finish the process, come to the store you selected and look for a Concierge in an orange shirt. We’ll help you complete your purchase, activate your new iPhone, and set it up for you.
Apart from the fact that I didn’t select a store, this was in sync with what the online store told me. A pain to have to visit an actual store, to be sure, but it didn’t sound like it would be too painful.
So today, I drove to the mall and visited the Apple Store. As soon as I entered, I spied an orange-shirted “concierge” and approached her. “Hello,” I said, “I tried to preorder an iPhone 3GS yesterday online, but it said it couldn’t do it, and I needed to seek out an orange-shirted person at an Apple Store. Can you help me with this?” She looked pained as she responded, “I’m sorry… we don’t actually have a system in place to pre-0rder the 3GS.” She went on to say that they did have a pre-order system for when the 3G was launched, and she assumed they would move that system over for the 3GS, but they had nothing now, and I should come back on the 19th. She also said that “lots” of people had been coming in today, who had also been told to visit a store to complete their purchase.
That just sucks out loud.
I’m trying really, really hard to throw money at Apple and they just won’t take it. They clearly underestimated how many people would try to pre-order online yesterday, otherwise they would have had more server bandwidth to handle it. The fact that they sent me (and others) an email telling me to go to a store to finish the process, when they have no such process in place, is just sloppy. I’m not happy about this one little bit, and I want people to know about it.
Does this mean I’m not going to buy a 3GS and, instead, go with a Pre or something else? Of course not, and Apple knows this….
Scala Gets Operator Overloading Right
02/20/2010 Update: I took this blog post and turned it into a presentation to the Atlanta Scala User Group, which I gave in January 2010. The slides from that presentation are here.
05/31/2009 Update: As Mads Andersen pointed out, in the example below, I had the Complex multiplication wrong. As I was working through the example in the book, I typed it incorrectly. I could argue that this blog post was not about my mastery of complex numbers, and was actually meant to show how operator overloading works in Scala, but in the interest of all-around correctness, I have updated the code to contain the proper implementation of complex number multiplication, and I have worked out the examples by hand using the formula on the Wikipedia page to ensure their accuracy. Now, on to the original article.
I’ve been intrigued by Scala for a while now, and I’m finally taking the time to learn it. As I was reading in my book yesterday, I came to the section on operator overloading. Now, this is a topic that developers who’ve been exposed to it feel very strongly about. It’s not quite as rough a discussion as vi vs. Emacs, but it’s close. Some say that operator overloading makes for more elegant code. Some say it just confuses things. I’ve always been in the elegant camp. I think if you can provide operators for your own classes that work intuitively, you ought to be able to do it. In Java, think about how nice BigDecimal would be to use if you had + and – instead of add() and subtract(). Of course, as with anything of power, you have to be careful not to abuse it. It would make no sense to provide a + operator on a Date class, since adding two dates together makes no sense. You have to be smart about it, but having the ability to provide operators for your own classes performing intuitive functions is a good thing.
So as I’m reading the section on operator overloading, it was nice to see that even though you can override the standard mathematical operators, Scala still maintains the proper precedence that everyone is used to. By this I mean that a + b * c will execute the multiplication first, then add the product of b and c to a. The reason this is interesting is because another language that I still love, Smalltalk, does it wrong (or at least, completely differently), and not just for overloaded operators. Smalltalk has no precedence for mathematical operators at all, ever. So a + b * c will execute the + operation on a, passing in b, and then execute the * operation on that result, passing in c. Always. Thus, 2 + 3 * 5 = 25 in Smalltalk, even though it should equal 17. To get 17, you’d have to write the equation as 2 + (3 * 5). I always found that strange.
The canonical example for operator overloading is a class to represent Complex numbers. I will not break with tradition and will, in fact, steal borrow the one from the book. Here, then, is the definition of the Complex class
class Complex(val real:Int, val imaginary:Int) {
def +(operand:Complex):Complex = {
new Complex(real + operand.real, imaginary + operand.imaginary)
}
def *(operand:Complex):Complex = {
new Complex(real * operand.real - imaginary * operand.imaginary,
real * operand.imaginary + imaginary * operand.real)
}
override def toString() = {
real + (if (imaginary < 0) "" else "+") + imaginary + "i"
}
}
Notice that we have overridden both the + and * operators. They each take another instance of Complex as an argument, do the proper operations and return a new instance of Complex as their result. Just as you would expect. Now, to exercise these operators, we have this
val c1 = new Complex(1, 2)
val c2 = new Complex(2, -3)
val c3 = c1 + c2
val res = c1 + c2 * c3
printf("(%s) + (%s) * (%s) = %s\n", c1, c2, c3, res)
val res1 = c1 + c2 * c3 + c1 * c2
printf("(%s) + (%s) * (%s) + (%s) * (%s) = %s\n", c1, c2, c3, c1, c2, res1)
Lines 5 and 9 are the interesting parts. The result of running these statements looks like this
(1+2i) + (2-3i) * (3-1i) = 4-9i
(1+2i) + (2-3i) * (3-1i) + (1+2i) * (2-3i) = 12-8i
which is exactly what you’d expect.
Now, C++ people are probably saying, “But C++ has always done it right!” Indeed. But languages like Smalltalk and Scala are far more fun to work in.
Skype For iPhone Is Full Of WIN!
We’re on vacation in Colonial Williamsburg, and the AT&T signal in and around our hotel sucks! This seems to be a common theme for me. At home, I have next to no AT&T signal. I swear, if it weren’t for the iPhone being such a loverly machine, I would never have gone with AT&T. Anyway, so we’re here in Williamsburg, and in the hotel, there is no cellular signal at all. But there is free, and fast, WiFi. So I fired up the Skype program on my iPhone and would you believe it worked a treat? It did. I have now made two calls with it. One to a restaurant in town, and the other to my brother-in-law back in GA to check on our dog. Both calls were crystal clear, with no lag or dropouts. I only have a 1G iPhone, so I can’t test it over the cellular network, but over WiFi, it was darn near perfect. I have a Skype unlimited subscription, so these calls were essnetially free. In any event, it was better than paying the $0.75 the hotel would have charged me for each call, plus whatever rate the local phone company charged. But beyond the cost, it was just plain cool!
I’ve been a fan of Skype for several years and we use it extensively where I work. I call into meetings and conference calls using it all the time, and I only very rarely have problems. I am now equally impressed with Skype for iPhone. Great job, guys! Keep up the great work.
Help Me With iPhone Dev Graphics Question, Please
Usually when I learn a new programming language or framework, I am plagued by the fact that I can’t think of anything to build with it, or I can only think of things that are too difficult. With iPhone development, I have two ideas for apps, both of which should be fairly easy to write. I’ve gotten a good start on the first app, but now I’ve hit a roadblock, and I’ve been stuck here for a while. I thought I’d ask for help.
Obviously I can’t disclose too much of what the app does, since I do eventually want to sell it in the App Store. Essentially, it allows for a very specific type of photo manipulation. I’ve got the basic UI built, and I’ve hooked into the camera framework, so you can either take a new photo, or use one you already took. I am displaying the photo in the main window, currently scaled to fit, but I will eventually add zoom and pan. I have the code written that allows the user to define a region of the photo to work on, by drawing a rectangle or ellipse. I draw the shape using Quartz 2D, which results in a red rectangle or ellipe drawn on top of the photo. So far, so good.
This is where I’m stuck. I need to do “something” to the bits in the photo in the region defined by the rectangle or ellipse and, at some point, a freehand shape. (Obviously I can’t reveal what the “something” is.) So, I have looked through the Quartz 2D docs and am trying to figure out how I can
- get the bits in the region defined by the user’s drawing
- swizzle the bits with my secret sauce to produce the desired effect
- get the swizzled bits back into the photo for display to the user
And here I sit. I have never done anything with graphics before, so this is all completely foreign to me. I can’t see how to do any of those three steps.
The next question, then, is should I be using OpenGL ES instead of Quartz 2D? The iPhone dev book I have taught a little bit of both, and the OpenGL stuff looked far more complicated than Quartz, which seemed like overkill for my situation. I don’t know.
I think I can accomplish what I want by creating an image mask, applying that to my original image, and then displaying the new image, but the mask creation function, CGImageMaskCreate, has me confused. I get most of the parameters, but I don’t understand the CGDataProviderRef parameter. Can anyone offer any sort of pointers to get me moving again? Are there any really in-depth Quartz 2D tutorials? The Apple docs on Quartz that I’ve read are very basic, and don’t really give examples.
Thanks for any help or pointers. I know I haven’t given you much to work with.







