7languages7weeks – what’s happened?!

Hello!

Ummm, so i’ve been a complete failure at week 5, the Erlang week.

I finished the Scala week and was really impressed by the concurrency and actor support, as well as the ability to parse XML as a top-level concept. I think i am actually a Scala convert: it’s one that i definitely want to look into more.

I have read the Erlang text but not done the exercises. I’ve been working away from home a lot recently, in Edinburgh. I wasn’t sleeping very well, and i found i’d become very lonely. This last week it was more important for me to spend time with new friends Will, Alistair, Kate, David, Adrian, Joe and Ryan. I’ve been juggling and slacklining, finding geocaches and going out for meals. I needed to do that for my own sanity, which turned out to be more important than studying Seven Languages in Seven Weeks. Thank you to everyone who has been a friend to me the last fortnight. Scottish people are nice! :D

Alberto has kindly agreed to lead tomorrow’s discussion. I’ll be there but i don’t feel able to direct the conversation because i didn’t do the Erlang exercises.

I am now back home for a fortnight and looking forward to getting back into studying for the last two weeks of Clojure and Haskell.

Advertisements

Week 4 Day 2 – Scala reveals its functional side

I’m a little behind this week, but i’m happy to be back into a bit more Scala. Today we learned about Scala’s functions, higher order functions (functions that take anonymous functions as parameters), currying functions (functions with multiple parameters that get transformed into other functions), and more about Lists, Maps and HashMaps.

On day 1 Scala reminded me strongly of Java. On day 2 it’s suddenly a lot more like Ruby. And then there are weird things that remind me of nothing i’ve ever seen before, such as “Everything inherits from ‘Any’, and ‘Nothing’ inherits from everything.” SRSLY, WUT?!

The foldLeft function

I find foldLeft very much like Ruby’s inject (or reduce). The book said this version would be harder to understand, but to me this looks just like Ruby. Here i am counting the number of letters in a list of words:

words.foldLeft(0) ((sum, word) => sum + word.length)

But Scala also has a weird version!

(0 /: words) {(sum, word) => sum + word.length }

I think /: is a very weird operator.

Replacing swear words

This was a hugely fun exercise! I chose Tim Minchin’s Fuck the Pope song which is the sweariest song i know! ;)

I used a Map for the swear words and their replacements. I found that a Map is unordered, so i converted it to a Sequence so that i could sort by length of swear word. (It helps to convert the longest words first, otherwise it would match partial words within longer words.)

The cleanVersion function went into a Censor trait that could be included into a RudeSong. It’s very much like a Ruby mixin, but i found that i needed a superclass Song to extend from, in order to mix in the Censor trait. I wish i could just do this:

class Song(val lyrics: String) with Censor

But that didn’t work. It had to be this:

class RudeSong(override val lyrics: String)
  extends Song(lyrics) with Censor

I found a way to read the song lyrics from a text file:

val lyrics = scala.io.Source.fromFile("lyrics.txt").mkString

You can find the full program at week4-scala/day2/curseWords.scala – please let me know if i can improve the style of the code at all, as i’m not at all familiar with Scala.

Here is a clean version of the last verse of Tim Minchin’s song!

So fornicate the mother lover, and fornicate you mother lover
If you’re still a mother loving papist.
If he covered for a single mother lover whos a kiddy-fornicator,
Fornicate the mother lover, he’s as evil as the rapist.
And if you look into your mother loving heart and tell me true
If this mother loving stupid freaking song offended you,
With its filthy freaking language and its freaking disrespect,
If it made you feel angry, go ahead and write a letter,
But if you find me more offensive than the freaking possibility
The pope protected priests when they were getting freaking fiddly
Then listen to me mother lover – this here is a fact,
You are just as morally misguided as that mother loving,
Power-hungry, self-aggrandized bigot in the stupid freaking hat.

And just because it’s a fun song, here’s the original!

Week 4 Day 1 – Scala time!

Now i come to another language that i know very little about. Here’s what i do know:

Scala is a sort of bridge between object oriented and functional paradigms. Much like C++ was a bridge between procedural and object oriented. These bridge languages allow two paradigms to coexist, providing a comfortable switch over for the programmer. In this stage of Seven Languages in Seven Weeks, we’re also getting a comfortable shift into the pure functional languages to come later.

Installing Scala

I know that Scala runs on the Java virtual machine, so i was expecting a hard time installing. Not so at all.

$ brew install scala

Homebrew downloaded it, probably added a symlink somewhere and that was it! Good to go!

Scala first impressions

No semicolons! woohoo!

This res1, res2 etc is interesting. i didn’t think on it too much until i got to assigning a variable:

scala> 5 != 2
res16: Boolean = true

scala> val a = 1
a: Int = 1

scala> 1 + 1
res17: Int = 2

scala> res17
res18: Int = 2

I noticed that we got ‘a’ instead of res17. Then i tried something else and there was res17. Then i figured out that res17 is a variable. I guess that’s useful to be able to look back and use a previous result.

There is a nice early hint at the way the object oriented and functional paradigms exist happily side-by-side: var is mutable, and val is immutable. Perfect!

I see that Scala takes a while to get started. I suppose it is compiling as it goes.

The book shows us how to define classes and instantiate objects. After our adventures into Io and Prolog, this feels a bit old-school. I’m looking forward to seeing Scala’s functional side.

My initial reaction is that i like Scala, and i certainly much prefer it to Java.

Exercise: tic-tac-toe

Or as i like to call it, zeros and crosses. What do tictacs and toes have to do with this game?!

Immediately on encountering this, i remember the Prolog sudoku solver and think, “Surely this problem would be better solved with Prolog?!” :)

Okay, so i have to take in a board and check whether somebody has won. I suppose i need an array of nine elements representing the squares on the board. In Scala, an array is called a List. Let’s start with the easiest case: an empty board and nobody has won.

class Tictactoe(val board: List[java.lang.String]) {
  def winner {
    println("Nobody won")
  }
}

val newGame = new Tictactoe(List("", "", "", "", "", "", "", "", ""))
newGame.winner

And to check that it runs:

$ scala tictactoe.scala
Nobody won

Okay, now we need to put a different message if somebody has won. So imagine the board

X | X | X
- - - - -
  | 0 |
- - - - -
  | 0 | 0

I am not known for my ascii art, by the way ;)

So a crude way to solve this is to check the first three elements, if they’re all the same, and they’re not empty, then that person won.

class Tictactoe(val board: List[java.lang.String]) {
  def winner {
    if(List(board(0), board(1), board(2)).toSet.size == 1
        && board(0) != "") {
      println(board(0) + " won!")
    } else {
      println("Nobody won")
    }
  }
}

val newGame = new Tictactoe(List("", "", "", "", "", "", "", "", ""))
newGame.winner

val xShouldWin = new Tictactoe(List("X", "X", "X", "", "0", "", "", "0", "0"))
xShouldWin.winner

I carried on like this for a little bit. I extracted a Triplet class for checking trios of square values within a board, to see if they were all the same.

I was pleased to find that, like Ruby and Io, you can return early from a method.

I’m not very proud of my code, but i’m not going to refactor too heavily tonight as i don’t yet know the Scala idioms. So here it is: week4-scala/day1/tictactoe.scala

Summary

It feels like Java but not. A good Java feel is its strong type checking. At some point i was writing a method that was to return a boolean and i’d done an if clause without an else. It caught that for me at compile time, to make sure i could guarantee a return value. That’s one of the things i like about Java.

But it feels very much easier to write than Java. I felt ready to get started straight away, with very little syntax cruft to hold me back. So i think i’m going to enjoy this Scala week!