Scala Sugar – Lists
If I want to become a real Scala Ninja, I am going to have change the way I think about coding. For the past 10 years I have been programming primarily using the object oriented paradigm. Although Scala supports pure object oriented programming, it is my desire to learn to program in Scala in a complete functional paradigm.
Of course, learning a new programming paradigm is not going to happen over night, it is going to take a bit of time. Over the course of the next few months, I am going to be posting a series of posts documenting my progress learning Scala. They will be written from the perspective of a “hardcore” Java programmer being enlightened by a sweet new language. I will write about all of the “sugar” Scala has to offer a Java programmer, and that is how I came up with title “Scala Sugar”.
In this first installment of Scala Sugar lets discuss one of the most fundamental concepts required to write any non-trivial program, namely Lists.
For the longest time, Lists in Java didn’t bother me at all, as they seemed “normal” to me. That was until I was introduced to dynamic languages a few years back. Now, Lists in Java seem extremely verbose to me as I wonder why in Java you can’t just create and populate a list with a single line of code. Lets look at our first Java vs Scala comparison.
Lets create a trivial list of three lowercase strings.
import java.util.ArrayList;
import java.util.List;
List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
In Java it takes a minimum of 6 lines of code to declare a list of 3 strings!
Now lets declare the same list in Scala.
val l = List("a", "b", "c")
Download Source: simpleLists.scala
Thats it, one line of code!
The most important things to pay attention to are:
- No need to import List in Scala, as most fundamental classes are imported by default in Scala
- You do not have to give ‘l’ a type in Scala. Scala uses Type inference which means that it can infer its type from the object it is pointing to. It is important to realize that Scala is statically typed, it just doesn’t require you to type your variables when you define them. The compiler is smart enough to figure it out.
- You can construct a list with elements in Scala, no need to “add” each element separately.
Even in this trivial example, you can start to see how clean and concise Scala is.
In my next post we will explore different ways to iterate over the lists.
References
- The code found in this post is hosted at github.com along with other sample Scala code.
- Scala List API
Scala reduceLeft
This post was updated on November 19, 2009.
As you know, during the past few weeks (time permitting), I have been spending time studying the Scala programming language. After reading the first few chapters of Programming In Scala, I have come across the first feature of Scala that would have been totally useful for me on one of my Java programming tasks a few months ago.
The actual programming task was quite complex, but for the purposes of this post, we will work with a dramatically simplified example. The simplified task is: given a list of Stocks figure out which one has the highest earnings per share.
Here is one way the problem can be solved in Scala:
class Stock(val ticker: String, var price: Double, var earnings: Double, var shares: Int) {
override def toString = ticker + " has eps of: " + eps + " with a price of " + price
def eps = earnings / shares
def >(that: Stock): Boolean = {eps > that.eps}
}
val portfolio = List(
new Stock("aapl", 203, 4.73E9, 878876000),
new Stock("ibm", 66, 1.23E10, 1384331000),
new Stock("goog", 465, 4.19E9, 314754113)
)
println(
portfolio.reduceLeft(
(s1, s2) => if (s1 > s2) s1 else s2
)
)
// goog has eps of: 13.31
Download Source: Stock.scala, reduceLeft.scala
If you have never seen Scala code before, this code will look quite foreign to you because there are a lot of concepts in Scala that are not present in Java. In a few weeks (again time permitting), will begin writing a series on Scala for Java programmers, but for right now, please bear with me, and try to follow along.
The most interesting things to me about this code are:
Line 04: You are reading it correct, that is operator overloading!- Correction: Scala doesn’t actually support “operator overloading”, in fact, “operators are not special language syntax”. In Scala any method can be an operator. What makes an operator an operator is how you use it. Example:
1 + 2 //operator 1.+2 //not operator
- Correction: Scala doesn’t actually support “operator overloading”, in fact, “operators are not special language syntax”. In Scala any method can be an operator. What makes an operator an operator is how you use it. Example:
- Line 07: It is great to be able to populate a list so easily without having to mess around with add methods.
- Line 14: This is the coolest feature of them all so far, the ability to reduce a list of elements down to one based on a binary operator.
This is just a small demonstration of the very basics of the Scala language. If you find this at all interesting, you can find out much more at scala-lang.org.
Note: obviously, this is not the most optimal Scala solution so if your a Scala guru, criticisms are welcome. I hope to come back to this example every few weeks, continually improving it as my knowledge of Scala grows.
References
- The code found in this post is hosted at github.com along with other sample Scala code.
Simple Applescript For The Traveling Mac
The Problem
You have a MacBook and a nice Apple Cinema display (this doesn’t sound like a problem so far), and you travel with the MacBook every day. When you open the lid of your MacBook you like to have the Dock on the left side of the screen giving you the most top to bottom space, but when you come home and connect the MacBook to your Cinema display and set up dual monitors, you want the dock on the bottom of the Cinema, not on the left side of the MacBook.
You don’t want to have to go in to preferences every time to switch the location. (or maybe you do?) For me it was becoming a very tedious task, so I began researching ways to automate it.
The Solution
Leverage Apple’s “Language of Automation”, Applescript to handle the task. Applescript has lots of useful hooks in to OS X.
The requirements for the script are quite simple:
- Obtain the current resolution of the primary monitor
- if the resolution is > 1900 (Cinema Display) configure the Dock for large display
- else configure the Dock for laptop display
For the moment, that is my goal, simple, yet time saving.
Step 1: Open AppleScript Editor
Step 2: Paste the following code in
Future requirements
- Figure out how to hook the script in to sleep/wake events in Snow Leopard.
- Customize more than just the Dock.
- Migrate it in to a startup script that brings up all necessary applications based upon current mood (reading/blogging/coding).
- Others???
Overall, I find Applescript a very easy way to automate things in Snow Leopard.
All of the source for this post can be found on github.com. Please feel free to fork and improve.
Enjoy.
iPhone 3.0 upgrade from beta 5 to final
For the past few months, I have been running the iPhone OS 3.0 betas on my iPhone without too many issues. Thus I assumed that when the final version of OS 3 was released, it would be easy to upgrade to it. This has not been the case. The current beta on my iPhone was beta 5, and then yesterday when the final version was announced, I assumed after a simple plug in to iTunes, I would be upgraded to the released version. Nope, iTunes kept telling me that I have the latest version of iPhone OS 3. It seems as though it is not checking the build number, only the OS level. The next thing I tried was doing a restore, this didn’t work either because it gave me an error saying it could not connect to the site to download the file.
Finally, after some Googling around, I found that others with the same problem circumvented it by putting their iPhone in recovery mode and then upgrading from there.
If you are currently running beta 5, you were supposed to upgrade to the GM version posted last week. I skipped it thinking their would be another release in the next few days with the final version. I have now learned that the GM version is the same as the final version. Unfortunately, now it is too late to download the GM from the developer website, as Apple has taken it down, and according to their documentation, you should obtain the final version through iTunes. Thus if you are in the same boat as me, on beta 5, you will have to install the latest version via recovery mode.
