Thursday, December 30, 2010

How to convert two Scala Lists into a Map

Update:

Since I posted this 24 hours ago, no fewer than 13 lovely people have left comments to let me know that this is actually far, far easier than I thought. There is a function on the List class (since 2.8.0, I think someone said), inherited from TraversableOnce, called toMap() which, if the sequence contains Tuple2s, will make a Map from them.

So the ideal solution is simply:
(keys zip values) toMap
Now the question is: How come everyone else knows about this and I didn't? :(

A couple of people also mentioned that you don't need to convert a List into an Array to be able to pass it into a var args method (but you still need the funky noise). Handy!

Thanks, everyone.


Original Post...

Not sure if this will ever be of use to anyone else, but I thought I'd put it out there just in case.

Problem:
You have a List/Seq of keys and a List/Seq of values, with the key at index n in one list matching the value at index n in the other. But what you really want is to convert them into a Map.

Solution:
Map(keys.zip(values).toArray: _*)

Explanation:
The steps here are:
  1. "Zip" the keys list with the values list, which creates a List of Tuple2 objects
  2. Convert the list of Tuples to an Array of Tuples. This is necessary because the Map object, which extends MapFactory, doesn't have any apply() methods that deal with lists but only the one that accepts a var args parameter of Tuple2s.
  3. Add this funky noise ": _*" which tells Scala to pass the Array as multiple varargs parameters, rather than trying to pass the whole Array as the first parameter.

Thursday, December 16, 2010

Graham's Guide to Learning Scala

It's a pretty widely-accepted view that, as a programmer, learning new languages is a Good Idea (tm). Most people with more than one language under their belt would say that learning new languages broadens your mind in ways that will positively affect the way you work, even if you never use that language again.

With the Christmas holidays coming up and many people likely to take some time off work, this end of the year presents a great opportunity to take some time out from your week-to-week programming grind and do some learning.

With that in mind, I present "Graham's Guide to Learning Scala". There are many, many resources on the web for learning about Scala. In fact, I think there's probably too many! It would be quite easy to start in the wrong place and quickly get discouraged.

So this is not yet another resource to add to the pile. Rather, this is a guided course through what I believe are some of the best resources for learning Scala, and in an order that I think will help a complete newbie pick it up quickly but without feeling overwhelmed.

And, best of all, it has 9 Steps!

[Note: Many of the resources have a slant towards teaching programmers that know Java, but I imagine if you know any other popular OO language like C++, C#, Ruby, Python, Objective-C or Smalltalk, you shouldn't have a problem picking it up.]

Are you ready? Here goes...

Step 1: Lay the Foundation

Read 'Introduction to the Scala Language' on scala-lang.org

This single page is a succinct but dense description of Scala and will let you know what you're in for, and why you should keep going.


Step 2: Get the Tools

Download and install the latest Scala release

Download and install the latest IntelliJ IDEA *Community Edition* release

Open IDEA and install the 'Scala' plugin


Step 3: Hello, World!

Create a new IDEA project with a Scala module.
Create a new file called HelloWorld.scala and paste in the following code:

object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}

Hit Ctrl-Shift-F10 to run it.
Congratulations! First Scala program done and dusted!


Step 4: Commute your Java skills to Scala

Read Daniel Spiewak's 'Scala for Java Refugees' series.

This should give you enough knowledge and experience with Scala syntax to be able to write Scala that does most of the things you can do in Java.

Make sure you enter the code examples into IDEA and try them out as you go. I suggest typing them out instead of copy-paste, because that's likely to give you exposure to common syntax mistakes and compiler errors.


Step 5: Open Your Eyes

Read through the 'Tour of Scala' on scala-lang.org

These short pages will give you some exposure to some of the more advanced features of Scala. Don't worry if you don't understand everything - just keep reading. You're not trying to learn how to use all these things, just to know that they're around.


Step 6: Learn the Basics, the Ins & the Outs

Read chapters 1 to 8 of Dean Wampler & Alex Payne's 'Programming Scala' (O'Reilly)

This is where the learning gets heavy. We're talking about more than half a book here. You'll learn everything from basic syntax (some of which you'll already know from the Refugees series) to Scala's more advanced patterns for object-oriented programming, an introduction to Scala's functional programming capabilities and some of the curly edges of Scala's type system.

Again, make sure you try out running the code samples in IDEA. I suggest you also have a play around with some of the concepts in your own little test classes. Any time you find yourself thinking "I wonder if I can use this feature to do this?", grab a keyboard and find out for yourself.


Step 7: Open the Dragon Scroll and Release your Scala Fu

Take a break from learning and do some hacking!

Think of a simple idea that you'd like to implement in Scala, then code it! (Seriously, I recommend keeping it REALLY simple.) If you can't think of something yourself, you can steal my idea of writing a function to perform word-wrapping.


Step 8: Take a Walk around the Grounds

Read the rest of 'Programming Scala' (chapters 9 to 14)

The rest of the book covers some of the peripheral libraries and concepts in Scala that contribute to making it a great language, like Agents for multi-threaded programming, "herding" XML input and output and building blocks for creating domain-specific languages, as well as reviewing some of the tools that have sprung up in the Scala ecosystem.


Step 9: Go Forth and Hack!

This is where the directed part of the journey ends, but hopefully it's only the first step.

What you do with Scala next is up to you, but by this point you know more than enough about Scala to start using it seriously at home or even at work, for fun, or for making some serious cash! If you do make some serious cash by hacking Scala, please remember how it all started and send a little monetary "Thank you" my way. ; )


Addendum: Getting Help

Perhaps it was a little presumptuous of me to effectively say "go away now and code". Chances are, you'll need some help as you keep experimenting, learning and doing more and more cool stuff with Scala.

The two best places that I've found to connect with other Scala users are the scala-user mailing list run by scala-lang.org and, for curly technical problems that you just can't figure out yourself, stackoverflow.com. Actually, reading through other people's Scala questions on Stack Overflow can also be a great way to pick up new ideas!


Want to learn more?

From Amazon...

From Book Depository...