Knowing Scala: Exercise 1

Taking my own 15 Exercises to Know A Programming Language as a starting point for my exploration of Scala…

The first set of exercises are right up the alley of a language with pattern-matching and list-processing:

Write a program that takes as its first argument one of the words ‘sum,’ ‘product,’ ‘mean,’ or ‘sqrt’ and for further arguments a series of numbers. The program applies the appropriate function to the series.

The first thing I did was write the functions:

[sourcecode lang=”scala”]
val args = List(1, 2, 3, 4, 5)
args.foldLeft(0)(_+_) //Sum
args.foldLeft(1)(_*_) //Product
args.sort(_ < _)(if(args.length % 2 == 0) args.length / 2 – 1 else args.length / 2) //Median
args.map(Math.sqrt(_)) //Sqrt
[/sourcecode]

Here the list-processing functions (highlighted in red) shine. The foldLeft() family of functions, also known as reduce, inject, or aggregate, applies a predicate to the elements of a data structure, accumulating a value. It’s hard to imagine cleaner code than what we have for the ‘sum’ and ‘product’ challenges. Similarly, the map() function is similarly clean-as-a-whistle for the ‘sqrt’ challenge. The ‘median’ challenge I’m less thrilled about: Passing in a custom comparator predicate to sort() is lovely, but my fingers typed in the C-language ternary operator :? and I was sorry to find that Scala doesn’t have it.

A big win for Scala is that I typed these in the Read-Evaluate-Print-Loop aka interactive console rather than having to deal with the overhead of a ‘real’ program and a edit-compile-test loop.

Moving on, the complete program follows:

[sourcecode lang=”scala”]
object Main
{
def main(args : Array[String])
{
val argList = List.fromArray(args)
val op = opMatch(argList.head)
val numList = argList.tail.map(java.lang.Double.parseDouble(_))
val result = op(numList)
print(result)
}

def sum(args : List[Double]) : Double = { args.foldLeft(0.0)(_+_) }

def product(args : List[Double]) : Double = { args.foldLeft(1.0)(_*_) }

def median(args : List[Double]) : Double =
{
args.sort(_ < _)(if(args.length % 2 == 0) args.length / 2 – 1 else args.length / 2)
}

def sqrt(args : List[Double]) : List[Double] = { args.map(Math.sqrt(_)) }

def opMatch(arg : String) : (List[Double]) => Any =
{
arg match
{
case "sum" => return sum
case "product" => return product
case "median" => return median
case "sqrt" => return sqrt
_ => throw new java.lang.IllegalArgumentException("Unrecognized operator " + arg)
}
}
}
[/sourcecode]

Let’s see… The translation of the REPL code into functions was very straightforward, although I have to admit to being somewhat disappointed that I could not use a type more abstract than Double. I don’t know if I could define a trait and then apply it retroactively to types in the java.lang package.

opMatch() shows some functional goodness — it’s declared as a function that takes a String and return a function that takes a List of Doubles and returns Any kind of object.

I’m not sure if I could do something more precise for my needs, like “returns a Double or List[Double]”. The pattern-matching in opMatch() is nice but not advanced.

If you have any observations to share, please comment below…

Good environmental news: First Hawaiian “golden gooney” chick to fly soon

Photo: US Fish & Wildlife Service

Raising Islands–Hawai’i science and environment: First Hawaiian “golden gooney” chick to fly soon.

How often do you get good environmental news?

I’m a bird geek. Or actually more of a romantic — I  shed a tear when I saw an Andean condor soaring above Machu Picchu (At that moment I was also very sore and weak with altitude sickness from hiking the Inca Trail, but still…). I also cried the first time I saw albatrosses doing their courtship ritual, which is not nearly as romantic, but was one of those things I’d first seen on some National Geographic special when I was 10.

Things I Learned From New Scientist This Week

Clever

Robot with corkscrew legs travels over rough terrain

Australia is considering a plan to make all cigarette packaging generic — no branding or design on the cigarettes or packages, just the name in a generic font. The cigarette companies are freaking out, obviously.

Interesting

A study seems to show “we see inaction as less immoral only because we typically lack proof that it was deliberate.” It makes me wonder about deliberate inaction in politics.

Elephants are evolving shorter or absent tusks in the face of selection pressure a.k.a. poachers.

Laughter may be a reward mechanism for recognizing incorrect explanations, i.e., to  aid the culling of mental models that are flawed.

Configuring Google +1 Button With Word Press and Bad Behavior Plugin

The very valuable Bad Behavior plugin for WordPress causes conflicts with Google’s recently introduced +1 button. The fix is very simple.

Symptoms: When you attempt to “+1” on a Word Press site that is using the Bad Behavior plugin, the +1 icon appears for a few seconds and then is replaced with a red exclamation point Error Icon that links to https://www.google.com/support/profiles/bin/answer.py?hl=en&answer=1199142&p=plusone_button_error

Solution: Whitelist the Google-owned netblock 74.125.0.0/16 in Bad Behavior’s “whitelist.inc.php” file:

  1. Confirm that I’m telling the truth about who owns that block: open a terminal and run a whois
  2. In your /wp-content/plugins/bad-behavior/bad-behavior folder open the file whitelist.inc.php and add the netblock to the $bb2_whitelist_ip_ranges array:

[sourcecode language=”php”]$bb2_whitelist_ip_ranges = array(
"64.191.203.34",    // Digg whitelisted as of 2.0.12
"208.67.217.130",    // Digg whitelisted as of 2.0.12
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"74.125.0.0/16",
//        "127.0.0.1",
);[/sourcecode]
Save the file to your server and you should be all set.

  1. Donate some money to the Bad Behavior plugin project…

Literate Programming: Python-Style

I don’t think literate programming is something that will ever enjoy widespread popularity, but for those who write about programming, it’s something devoutly to be wished. It might be a good match for Python, which is a nice language for data exploration and demonstrating algorithms and techniques. This tool: pyreport: generate reports out of python scripts can be used for literate programming in Python.