Scala – Day 1

I was looking forward to Chapter 5 of Seven Languages in Seven Weeks: Scala. I’ve heard quite a bit about it in the last few weeks at various user groups, and I’m hoping to get my hands on it at some point in my upcoming work with Atlassian, so this was a good time to dive in. As a personality, Scala is assigned Edward Scissorhands in the book: “awkward, and sometimes amazing”.

I tried at first to install it with Homebrew, which just failed with a 404, so I downloaded the package and installed it manually, which worked fine.

Day 1 was pretty straightforward – type a few things into the console and have a look at what you get back. This chapter delves into loops and ranges and compares Scala with both Java and Ruby, finishing up with some simple class definitions and traits. As with most of the chapters so far, it very quickly introduces a lot of ideas – not much detail, but enough to get me thinking.

In the self study for Day 1, the first questions are reasonably simple.

  1. Here’s a link to the Scala API
  2. There are lots of blog posts comparing java to scala, mostly just one aspect. I liked this write up based on a year of experience with Scala.
  3. A discussion of val versus var.

The next challenge was to write a game that will take a tic-tac-toe board (noughts and crosses for the Brits …) and determine a winner. The bonus part of the challenge would be to make it into a game that two people could play, so I attacked this part first.

I started off using Sublime Text 2, then decided to switch to IntelliJ with the Scala plugin. I like Sublime, but was hoping IntelliJ would give me better auto completion, refactoring tools and keyboard shortcuts. It seems to work OK – I had to point IntelliJ towards my Scala installation, and it is still popping up with some errors although it does compile and run just fine. Perhaps in Day 2 and 3 I’ll dig into those a bit more.

In writing the code for the game, I tripped up on a few things. I had Martin Odersky’s book Programming in Scala to refer to as well, which helped me solve most things really quickly.

Firstly that the chapter hadn’t covered how to return a specific type from a function. Scala doesn’t require the return keyword, but if you don’t specify a return value, it returns Unit().

Here’s a function without a return type:

def myMethod() {

}

And with:

def myMethod() : Int = {

}

In my next mistake, I tried to create an array and then add items to it – Arrays are mutable in Scala, but you can’t change the size of them. I didn’t even have a good reason for doing this, except that I thought it would make the code prettier, so I changed it to a List (immutable) instead. And it looked fine :)

I don’t know a lot about functional programming yet, so I did have a couple of classes in my solution. I wanted to make sure I had no mutable objects though.

When I finished my initial solution, I had three files – I ended up taking the lazy way of copying all the classes into the one file and running it from the terminal with scala tictactoe.scala. Here’s the initial attempt. I like that it doesn’t have any mutable objects, it’s simple, I don’t have to worry about blanks, and the simple map method to get the positions. I don’t much like the magic winning combinations in the Judge class, and I don’t like that if you don’t enter the moves in a valid format it will barf.

Next challenge: on to Day 2, and also trying to extend the tic-tac-toe game for the bonus challenge!

Finishing up with Io

As I reached Day 2 with Io, I continued to struggle with the syntax, in particular temptation to write object.method instead of dropping the ‘.’. I felt that I was starting to get some of the concepts of the language, the ability to rewrite core methods and override Operators.

However, I have also struggled throughout Day 2 and Day 3 with the lack of easily available documentation – the reference and guide on the main IO website did not seem to explain many of the things I needed to know, including how to read input from the console. I resorted in some cases to “cheating” by reading other people’s solutions to the exercises (although it’s not really cheating, since the point is to learn :)).

As I wrote my solutions, particularly the longer ones, they felt slightly clumsy – as though I wasn’t taking advantage of Io’s strengths. In the middle of Day 2 and start of Day 3, I really wasn’t enjoying working with the language, although by the end of Day 3 when I introduced the new Xml_Element object, it felt more natural. I’m glad I finished the chapter, although I’m still not really sure where I would use Io.

Overall, the main thing I’ve got out of the book so far is a greater understanding of meta-programming, which I’m hoping will help me take better approaches to new programming problems.

All of my solutions are on Github Gists:

Here are some highlights from the difficulties I ran into …

I was baffled for Day 2, Exercise 2 as to how to keep the original division method, but a quick internet search (and a minor cheat) revealed the solution: I needed to store the original division method in another variable:

When I reached Exercise 7, I discovered from other solutions that serialization in IO is actually really, really easy. All objects have a serialized method that writes it out to a string. When reading the object back from a file, all that was needed was the assign the results of the doFile("filename.txt") method to a new object. Writing to files is easy too – here’s the full solution:

For Exercise 8, I spent a considerable amount of time trying to find out how to read input from the console – turns out you can use File standardInput readLine. This gives you a string, so you need to use asNumber to complete this exercise.

Day 3, Exercise 1, was a massive struggle – at first I could not figure out how to pass the right indent, and I ended up looking around at some other examples before I figured out that I needed to:

  1. Write the parent node
  2. Add one to the indent
  3. Process the child nodes
  4. Remove one from the indent
  5. Close the parent node

I also discovered that using indent := indent + 1 doesn’t work – I guess you lose the reference to indent, so you need to do indent = indent + 1. Here’s the finished code:

In Exercise 2, I discovered after some internet searching and experimenting that Io has two built in methods: curlyBrackets (as used in the book) and squareBrackets – these can both be overridden to allow lists or maps, or anything else, to be created using {} or []. I guess this might be obvious to some people, but I was quite confused by it!

Here’s the list code:

The final exercise, adding attributes to the XML Builder, had me stumped for some time – in fact, I took a break from it overnight and a solution came to me in the shower :) My difficulty was figuring out when to write the contents of the XML node, I didn’t want a separate method but couldn’t write out the contents inside the loop.

The final solution still feels slightly clumsy but it does work (indents and all):

IO – Day 1

The group as a whole seems to have slowed down a bit on IO, with only a few of us sharing our Day 1 experiences. Installation has bitten a few people. I was lucky in that I was able to install it painlessly on OSX using Homebrew.

My next challenge with IO was figuring out the syntax for comments – turns out it’s a double slash: //

The homework: there was a lot of questions to answer, so I figured it was better to complete it in a blog post rather than a gist.

Stuff to find

Example problems
I wasn’t sure if they are looking for puzzles to solve, or problems with the IO codebase. I couldn’t find the former, but here are some problems with the codebase: http://en.wikibooks.org/wiki/Io_Programming/Pitfalls

Community
Yahoo group: http://tech.groups.yahoo.com/group/iolanguage/

Style guide
http://en.wikibooks.org/wiki/Io_Programming/Io_Style_Guide

Questions to answer

  1. IO is strongly typed. The following commented out code causes an error because “one” is not a number.
  2. All are true:
  3. Use slotNames:
  4. ::= Creates slot, creates setter, assigns value
    := Creates slot, assigns value
    = Assigns value to slot if it exists, otherwise raises exception

    The output of the slotNames in the code below reveals that Elf has the following slots: type, weapon, setWeapon, name

Stuff to Do

  1. To run an IO program from a file, just open terminal and type io filename.io.
  2. To execute the code in a given slot, simply call the slot.

Note: for the last piece of homework, I was trying to think of what to write code about. I recently moved into a new flat, and my new housemate has a small, very cute dog, who has just discovered a new game: fling his smackos under the bed, and then bark at it until she comes to retrieve it for him. I decided to write a very simplified version of that :)

Seven Languages Week 1: Ruby

Week one of the seven languages is complete!

Having the support of the study group was great – motivating but without being too much. I was amazed at the breadth of the solutions, especially to the homework for Day 1 and Day 2.

Day 3, I was a bit underwhelmed by – the final part of the chapter introduced a lot of interesting techniques with meta-programming and modules, but the problem set didn’t really seem to challenge me to think too much about them.

The book encouraged me to look at the API to try and find solutions for different problems. Having the study group made this aspect even better, because we often found different things – for example, collect and zip methods for arrays. James in particular found some very short and neat ways to solve the problems.

Overall I think I like Ruby even more after doing this. It has so much “syntactic sugar”, and I definitely have a sweet tooth! Overall I’ve learned that while you can use Ruby to write programs in a rather boring, more Java-esque style, there is almost always a much neater, Ruby-ish way of doing it. I only wish I had more time and opportunities to learn it properly.

My highlights:

  • Day 1 reminded me of the usefulness of ranges
  • Quick ways to convert between hashes and arrays in Day 2:
  • Discovering the ‘grep’ method in Enumerable from James’ day 2 solution.
  • Finally getting a better understanding of modules (still far from perfect, but I definitely get them far better than before)
  • Learning the ‘zip’ method for arrays – although still not sure I completely understand how to use it!

My solutions are here: https://gist.github.com/jocranford

7 Languages in 7 Weeks – The Next Study Group …

I was inspired a while ago by Daniel Temme’s experience working through the book Seven Languages in Seven Weeks as part of a study group organised by Aimee Daniels, and together with James Doig (a colleague and regular pair on my current project!) we decided to start a new one. We’ve got a Google group and planning to use Google+ hangouts, blogs and twitter (with the tag 7languages7weeks or through this account).

We’ve agreed to kick off on October 24th with Chapter 1, which covers Ruby. I’ve had a sneak peek at the book, a bit of a giggle at the comparison of Ruby the programming language to Mary Poppins, the magic British nanny, and I’m excited now to get started. I haven’t done very much functional programming, and the book promises to challenge me, and to teach interesting aspects of each language. We’ve agreed to take it a little slower for the first couple of chapters and see how things go.

Our group has grown to around fifteen people, divided about half and half between ThoughtWorkers and Skyscanners, and also includes one post-technical project manager – very impressive! There’s still time to join, so please leave a comment or contact me via twitter if you’re interested.