Archive for January, 2008

Scalaz Demo Code

Friday, January 25th, 2008

Here are some examples demonstrating the use of the Scalaz extension to the Scala libraries.

http://tinyurl.com/2tf5ma Boolean (additional functions i.e. implication)
http://tinyurl.com/3×4el9 Effect (side-effect)
http://tinyurl.com/3yf6vr File (reading Files)
http://tinyurl.com/2s74km Either (disjoint union)
http://tinyurl.com/3xlpbn Monad
http://tinyurl.com/2sbn2h Foldable (Catamorphism)
http://tinyurl.com/326rdx Paramorphism
http://tinyurl.com/2n8uh3 Validation (Either[A, _] lift)
http://tinyurl.com/2r5g6r Memoisation (0-1 Knapsack DPA)

Scala operator names

Tuesday, January 22nd, 2008

Infix (least to highest precedence)

|
^
&
< >
= !
:
+ -
* / %
~

Postfix (unary_)

+
-
!
~

Operators ending with colon (:) are right-associative.

scala.Option Cheat Sheet

Wednesday, January 16th, 2008


Many people who are coming in to Scala first encounter the Option type, which may be thought of (among other things) as a type-safe null. They also encounter pattern matching as both a new and (relatively) powerful concept, but also one that is easy to understand. This leads to quite a lot of use of pattern matching and often excessively so in what I have observed.

Particularly with a type as trivial as Option, it is almost always possible to do away with pattern matching by using a higher-order function. Use of this function is typically preferred over pattern matching as tighter code. In fact, it is important to observe that it is possible to encapsulate all forms of pattern matching over Option with one simple higher-order function:

def option[A, X](o: Option[A])(none: => X, some: => A => X): X = ...

Then, all functions can be written in terms of this one and needn’t pattern match at all. For example, consider Option.map:

def map[A, B](o: Option[A], f: A => B) =
  option(o, None, a => Some(f(a)))

In this post, I am going to give some common uses of pattern matching, which many developers might find themselves performing, followed by the use of a function that already exists on Option that encapsulates that given form of pattern matching. If you find yourself using pattern matching in a form not listed below, but feel it could be abstracted, then chances are that such a function exists in the Scalaz extension to scala.Option.

I will use the identifier foo below to denote any particular function, including many functions composed, for example, foo(x) may represent the composition of two functions f and g: f(g(x)). I also use the identifier option to denote any value of the type scala.Option.

I hope this helps :)

  • flatMap

    option match {
      case None => None
      case Some(x) => foo(x)
    }

    This code is equivalent to:

    option.flatMap(foo(_))
  • map

    option match {
      case None => None
      case Some(x) => Some(foo(x))
    }

    This code is equivalent to:

    option.map(foo(_))
  • foreach

    option match {
      case None => {}
      case Some(x) => foo(x)
    }

    This code is equivalent to:

    option.foreach(foo(_))
  • isDefined

    option match {
      case None => false
      case Some(_) => true
    }

    This code is equivalent to:

    option.isDefined
  • isEmpty

    option match {
      case None => true
      case Some(_) => false
    }

    This code is equivalent to:

    option.isEmpty
  • forall

    option match {
      case None => true
      case Some(x) => foo(x)
    }

    This code is equivalent to:

    option.forall(foo(_))
  • exists

    option match {
      case None => false
      case Some(x) => foo(x)
    }

    This code is equivalent to:

    option.exists(foo(_))
  • orElse

    option match {
      case None => foo
      case Some(x) => Some(x)
    }

    This code is equivalent to:

    option.OrElse(foo)
  • getOrElse

    option match {
      case None => foo
      case Some(x) => x
    }

    This code is equivalent to:

    option.getOrElse(foo)

    toList

    option match {
      case None => Nil
      case Some(x) => x :: Nil
    }
    option.toList

scala.List.foldLeft for Java programmers

Tuesday, January 15th, 2008

I recently ran another Scala training course and I produced a hand-out that seemed to help people understand what a foldLeft is. Here is a brief explanation of it.

Suppose you have the following Java code:

B b = start
 
for(final A a : listOfA) {
  b = method(b, a);
}
 
return b;

You can have any value for start, method and listOfA. Also, method may ignore any of its arguments or even not have them passed at all. You’ll notice that a lot of Java code is written this way, so it would be fair to say that “left folds occur a lot in Java”, despite being encoded as loops.

The above Java code is equivalent to the following Scala code, again for all values of the given identifiers (so long as they type check of course):

listOfA.foldLeft(start)(method)

…which is also equivalent to:

(start /: listOfA)(method)

…which by the way, is a perfectly sound approach to performing a list reduction, despite what some clowns rubbish on with.

That’s all, hope it helped :)

Offending Religiosity

Tuesday, January 1st, 2008

In my recent post, I made the following introductory statement:

Scala is a far superior language to Java.

Sadly, but most predictably, some people took issue with this fact. It seems I have “stepped on someone’s meme” so-to-speak. Programming languages, unfortunately, have formed cliques who defend their territory with classic religious devotion.

It is certainly not difficult to conceive two programming languages where one is inferior to the other, and so long as neither language has any devoted followers, it is acceptable and makes perfect sense to anyone willing to hear it. I invent a language called Plus and it has one function + and integral literals; I invent another language PlusMinus and it has two functions, + and - and integral literals also. PlusMinus is superior to Plus.

We can traverse the futile path of “Actually, whether PlusMinus is superior to Plus depends on whether - is of any value. The non-existence of the - function in Plus may make it superior under some circumstances”, but I’m hoping, perhaps too optimistically, any objectors can see straight through this misnomer.

It is cases like these where the similarities to the typical religious organisations becomes astounding. I am charged with religiosity, because I am completely atheistic (i.e. null hypothesis) about my meme membership, by those who themselves are more religious than ever! Something about pots, kettles and blackness seems apt here. Furthermore, it is quite often the case that when the charges roll in, in defence of Java, those making the charges know Java quite poorly anyway (most so-called Java programmers do in my observations) — another religious theme that seems to be deeply embedded.

The status of “Java” has been artificially elevated by its groupthink members such that any attack or suggestion of inferiority is reviled, even if the suggestion is perfectly rational and able to be supported with evidence. I could simply discredit their understanding of their belief system by demonstrating how little they know about it (I am always surprised at how easy this is), but it does seem somewhat distasteful. Alternatively, I could present aforementioned evidence, only to have it (predictably so) misunderstood and misrepresented in various forms of logical fallacy.

No, I’d rather work toward abandoning religiosity itself and demonstrating that reason trumps. After all, like most religious memberships, I don’t think these charges have any kind of malicious intent or deceptive techniques behind them, invoke Hanlon’s Razor:

Never attribute to malice that which can be adequately explained by stupidity.

Doomsday in Scala

Tuesday, January 1st, 2008

Just for kicks, from http://en.wikipedia.org/wiki/Doomsday_algorithm

sealed trait Day {
  def +(n: Int): Day
}
final case object Sunday extends Day {
  override def +(n: Int) = n % 7 match {
    case 0 => Sunday
    case 1 => Monday
    case 2 => Tuesday
    case 3 => Wednesday
    case 4 => Thursday
    case 5 => Friday
    case 6 => Saturday
  }
}
final case object Monday extends Day {
  override def +(n: Int) = n % 7 match {
    case 6 => Sunday
    case 0 => Monday
    case 1 => Tuesday
    case 2 => Wednesday
    case 3 => Thursday
    case 4 => Friday
    case 5 => Saturday
  }
}
final case object Tuesday extends Day {
  override def +(n: Int) = n % 7 match {
    case 5 => Sunday
    case 6 => Monday
    case 0 => Tuesday
    case 1 => Wednesday
    case 2 => Thursday
    case 3 => Friday
    case 4 => Saturday
  }
}
final case object Wednesday extends Day {
  override def +(n: Int) = n % 7 match {
    case 4 => Sunday
    case 5 => Monday
    case 6 => Tuesday
    case 0 => Wednesday
    case 1 => Thursday
    case 2 => Friday
    case 3 => Saturday
  }
}
final case object Thursday extends Day {
  override def +(n: Int) = n % 7 match {
    case 3 => Sunday
    case 4 => Monday
    case 5 => Tuesday
    case 6 => Wednesday
    case 0 => Thursday
    case 1 => Friday
    case 2 => Saturday
  }
}
final case object Friday extends Day {
  override def +(n: Int) = n % 7 match {
    case 2 => Sunday
    case 3 => Monday
    case 4 => Tuesday
    case 5 => Wednesday
    case 6 => Thursday
    case 0 => Friday
    case 1 => Saturday
  }
}
final case object Saturday extends Day {
  override def +(n: Int) = n % 7 match {
    case 1 => Sunday
    case 2 => Monday
    case 3 => Tuesday
    case 4 => Wednesday
    case 5 => Thursday
    case 6 => Friday
    case 7 => Saturday
  }
}
 
// From http://en.wikipedia.org/wiki/Doomsday_algorithm
object Doomsday {
  def anchor(y: Int) = y / 100 % 4 match {
    case 0 => Tuesday
    case 1 => Sunday
    case 2 => Friday
    case 3 => Wednesday
  }
 
  def doomsday(y: Int) = {
    val a = y % 100 / 12
    val b = y % 100 % 12
    val c = b / 4
    val d = a + b + c
    anchor(y) + d
  }
}

scala> import Doomsday._
import Doomsday._

scala> doomsday(1966)
res0: Day = Monday

scala> doomsday(2008)
res1: Day = Friday