Showing posts with label scala. Show all posts
Showing posts with label scala. Show all posts

Friday, June 4, 2010

Formatting Console Output in Scala

So it's midnight and I'm programming Scala (heh).  I'm actually starting to be able to write little scripts in Scala.  Here's a quick one that I put together, inspired by Chapter 3 of "Programming Scala" which reads a source code file and formats the file to the screen with line numbers.



I tried to be as functional as possible.  The "formatSourceLine" I felt was getting close to the concept, using recursion, immutable values, and always returning a value (avoiding the side effect of printing from within the function).

The actual output from this script is:

D:\Development\Scala>scala file.scala file.scala

    1 | import scala.io.Source
    2 |
    3 | if (args.length > 0) {
    4 |
    5 |     def formatSourcePrefix(line: Int, suffix: String, max: Int = 5):
    6 |         var prefix: String = ""
    7 |         for (i <- 1 to (max - line.toString.length))
    8 |             prefix += " "
    9 |         prefix + line.toString + suffix
   10 |     }
   11 |
   12 |     def formatSourceLine(lines: List[String], line: Int = 1, 
   13 |         val out = output + formatSourcePrefix(line, " | ")
   14 |         if (lines.length > 1)
   15 |             formatSourceLine(lines.tail, line + 1, out)
   16 |         else
   17 |             out
   18 |     }
   19 |
   20 |     // Read file from disk
   21 |     val lines = Source.fromPath(args(0)).getLines().toList
   22 |
   23 |     // Print results to screen
   24 |     println
   25 |     print(formatSourceLine(lines))
   26 |
   27 | }
   28 | else {
   29 |     // Print out proper syntax
   30 |     Console.err.println
   31 |     Console.err.println("scala file.scala [filename]")
   32 | }

Saturday, May 29, 2010

The Difference a Space Can Make

How can you print the string value of a floating point value of 5 in Scala?

scala> 5.toString  // Wrong!
res16: java.lang.String = 5

scala> 5. toString
res17: java.lang.String = 5.0

In the first line scala counts the "." as syntax for "toString method of Integer 5".  The second line uses the "toString" method in infix notation, applying the toString method against the floating point value of 5.0.

Here's another example where a space can make a big difference in type:

scala> 4.+(1)
res20: Double = 5.0

scala> 4 .+(1)
res21: Int = 5

Abstract Types in Scala

Whenever I learn new programming languages, there is invariably features of the language that will surprise me.  One of those in Scala (one of many actually) is abstract types.  When I first read the textual description of an abstract type, I wondered what use it would ever entail.  However, the authors of Programming Scala gave a very clear example of proper use.

This code snippet comes from Chapter 2 of the book.

Starting with an abstract class, we can declare an abstract type.  In this case, type "In" on our class "BulkReader" is abstract.  It's there, but it does not have a concrete type associated with it.  Yet, our value "Source" is typed as type "In".  How can this be?

abstract class BulkReader {
  type In
  val source: In
  def read: String
}
The magic comes when we declare a concrete version of "BulkReader" and can assign a concrete type to "In":

class StringBulkReader(val source: String) extends BulkReader {
  type In = String
  def read = source
}

class FileBulkReader(val source: File) extends BulkReader {
  type In = File
  def read = {
    val in = new BufferedInputStream(new FileInputStream(source))
    val numBytes = in.available()
    val bytes = new Array[Byte](numBytes)
    in.read(bytes, 0, numBytes)
    new String(bytes)
  }
}
Very cool!  In our two concrete instances of "BulkReader" we assigned two different types to our abstract type "In".  Note that the value typed as In, "source" is actually part of the concrete class's constructor which is, at this point for me, completely mind bending in terms of flexibility towards class design.

I have a feeling it will take me some time to get used to this notion and power before I really start to design code that makes use of it.

Wednesday, May 26, 2010

Language of the Summer: Scala?

I've been quite fascinated with Haskell as a language.  It's purely functional, ridiculously strict typing, and algebraic syntax were completely foreign to me before I began learning about it.  I wouldn't say that I learned Haskell, but I did learn about it.  I learned enough to know that it's a bit over my head at this point and that I need a better theoretical foundation before I attempt to tackle it again.

So in the mean time I wanted to take on something more transitional.  I had considered F#.  It seems like a great choice, especially since I already know C# and am familiar with the .NET platform.  But it's a Microsoft language and I was hoping for something more portable (actually, I'm harboring a secret desire to use a functional programming language to one day code for Lego Mindstorms NXT with).

I happened to stumble upon Lift again yesterday.  I had heard about it before when I was looking at other web frameworks after watching a keynote from the author of Seaside at Djangocon.

However, I realized something important about Lift and Scala which I had never caught before: Scala compiles to java bytecode.  Java can be run on Google App Engine.  I can use Scala/Lift to write for App Engine.

Suddenly I'm hooked.  Oh, awesome, and the book "Programming Scala" is available freely online.  Mmmm... looks like I have my reading for my traveling this summer.

  © Blogger template 'Minimalist G' by Ourblogtemplates.com 2008

Back to TOP