30Jan

# Scala for the Impatient, chapter 2

Posted by Elf Sternberg as Uncategorized

Below are my answers for SftI Chapter 2. I’ve also included some commentary on interesting things I realized as I did the problems.

`1. def signum(n: Int) = { if (n == 0) 0 else if (n > 0) 1 else -1 }`
`2. No value.  Unit.`
`3. def x = y = 1.`

This is equivalent to:

`def x = { y = 1 }`

Look at the example function on page 20 to understand why. Appreciate that functions can have a signature of n parameters, zero parameters, or noparameters. It’s that last form that Scala is exploiting here. The third example in the section on laziness on page 24 provides the other half of the hint.

`4. for(i <- 10.to(0, -1)) println(i)`

I guessed the syntax for the step parameter. It’s nice to know Scala’s at least as useful as Perl.

`5. def countdown(n: Int) { for(i <- n.to(0, -1)) println(i) }`

Note that there’s no equals sign. This function is pure side effect.

`6. def unimath(s: String) { var x = 1 ; for (i <- s) { x = x * i }; println(x); }`
`7. def unimath2(s: String) { println(s.foldLeft(1)((b, a) => b*a)) }`

It’s important to know that I have no idea what that arrow operator is there; I looked up the syntax for foldLeft on line, after recognizing it from Javascript’s ubiquitous underscore library, of all things. It looks like a lambda expression. The book doesn’t help, but the cheatsheetdoes say this is used for anonymous functions. There is no #8. I didn’t realize I wasn’t supposed to do #6 and #7 as literals rather than functions. Sorry, competence is a habit.

```def unimath3(s: String) {
def unimathhelper(s: String, i: Int):Int = {
if (s.length == 0) i else unimathhelper(s.tail, i * s.head)
}
println(unimathhelper(s, 1))
}```

This one is cool for all sorts of reasons. Not only does it do a lovely recursion, but I love that the whole head/tail thing is there, and I am especially happy to see that nested functions work in Scala, since it looks like one of those languages that ought to have it.

```def powers(x: Double, n: Int):Double = {
if (n == 0) 1 else
{
if (n < 0) (1 / powers(x, (-1 * n))) else
{
if ((n % 2) == 0) {
val y = powers(x, n / 2)
y * y
} else {
x * powers(x, n - 1)
}
}
}
}```

I’m a little annoyed by this one because it’s arbitrary: the definition in the book doesn’t tell you what you’re looking for, or why. That said, it was a fairly easy, if annoying, cascade of if statements.  And hey, it’s entirely made of immutable expressions.  I like that.

January 2013
M T W T F S S
« Nov   Feb »
123456
78910111213
14151617181920
21222324252627
28293031