tags:

views:

300

answers:

1

I am studying JavaFX Script and trying to compare it to Scala, which is another very interesting new language for the Java platform.

In the official Scala site I found this example, which is a Quick Sort implementation. I then wrote the following equivalent JavaFX Script program (using NetBeans IDE 6.7.1):

package examples;

function sort(a: Integer[]): Integer[] {
   if (sizeof a < 2)
      a
   else {
      def pivot = a[sizeof a / 2];
      [sort(a[n | n < pivot]), a[n | n == pivot], sort(a[n | n > pivot])];
   }
}

function run(args: String[]) {
   def xs = [6, 2, 8, 5, 1];
   println(xs);
   println(sort(xs));
}

Both functional programs are very similar, but I like the JavaFX version better. Those "_" and ":::" parts in the Scala version don't look very appealing to me...

Of course, there is a lot more to both languages, so I am looking for more examples. Does anybody know where I can find some? Or even better, post other examples here?

+3  A: 

Keep in mind that the Scala syntax is flexible. You could have easily written it without the ":::" and "_" this way:

package example

/** Quick sort, functional style */
object sort1 {
  def sort(a: List[Int]): List[Int] = {
    if (a.length < 2)
      a
    else {
      val pivot = a(a.length / 2)
      List.concat(
        sort( a.filter( n => n <  pivot ) ),
              a.filter( n => n == pivot ),
        sort( a.filter( n => n >  pivot ) )
      )
    }
  }
  def main(args: Array[String]) {
    val xs = List(6, 2, 8, 5, 1)
    println(xs)
    println(sort(xs))
  }
}

For code comparisons, I usually look at http://rosettacode.org/ It has several Scala examples, but no JavaFX ones. If you get far in this project, please take the time to add some JavaFX to that site. :-)

Mitch Blevins
Thanks, great answer! I imagined Scala should also provide named variables instead of the default "_"; in the end, the code is very close to JavaFX Script. (I guess these languages really are the future for the JVM.) I will see about contributing some code to that site.
Rogerio
I contributed the first JavaFX Script example to Rosetta Code: http://rosettacode.org/wiki/Simple_Windowed_Application#JavaFX_Script.
Rogerio