Thursday, March 12, 2009

Beginning Scala -- Author Interview with David Pollak

There are several good looking Scala books on their way to market. I'd like to help you get an early look at the books and their authors, so I'm working on a series of Scala author interviews for the FP side of On Ruby. Here's the first of several interviews.

I've spent some time talking with David Pollak (@dpp) about his upcoming book from Apress, Beginning Scala (also available, electronicly, as an Alpha book from Apress). Read on to see what he has to say.


Functional Programming languages seem to be an increasingly popular topic. Why? What do FP languages teach or do for us?

David I came to Scala via Ruby. I was doing some Ruby and some Java coding (I've been doing Java since 1996). My Java code started taking on a "Ruby Flavor" in that I was passing around a lot of code blocks. In Ruby, passing code block, lambdas, etc. is super-simple. In Java, I was creating lots of anonymous inner classes and passing them around... it was a syntactic disaster.

In Scala, passing a function, a block of code, as a parameter is as easy and syntactically pleasing as it is in Ruby (or nearly so... Charlie Nutter has been barfing all over Scala's syntax lately.) This is the first part of what I understand FP to be. So, in a way, Ruby is a functional language.

In addition to the simple ability to pass code blocks as parameters, other touch-stones of FP style coding are:

  • Immutable data structures
  • Pattern Matching
  • Optionally, a math-driven type system
  • Optionally, lazy evaluation

Scala's default collections classes are immutable. Once an instance has been created, the value of that instance, whether is be a List, a Map (dictionary), etc. never changes. This is familiar to Java programmers. Java's String class is immutable. Once you create a String, you can never change it. Python requires immutable data structures for keys to dictionaries. Immutability introduces a new way of approaching a program. One thinks about methods as things that take input and return output and will always return the same output given the same input. In Ruby, String is mutable and there have been many a bug in my programs because some other method changed the value of a String out from under me.

Pattern matching provides a powerful way to use declarative syntax to express business logic. I'm include an example in the idomatic section of intercepting an incoming HTTP request using pattern matching.

Scala has a very powerful type system including a type inferencer. What that means is that you can define very powerful rules (e.g, when building a query, you can only pass a String into a column that is a VARCHAR) in the library, but the end-user gets the syntactic simplicity of Ruby.

Scala supports lazy evaluation at the language level and in the libraries. This means that only elements that are actually accessed are computed.

Functional languages teach us how to think in terms of transformation rather than getting/setting. Functional programming focuses the developer's eyes and mind on the business logic rather than the boilerplate of flow of control. Functional programming gives us different kinds of abstractions to compose than objects. Composing functions and performing operations on collections just as easily as performing operations on single items changes the focus of development to logic rather than mechanisms.

What makes Scala the right FP language for people to pick up?

David Scala along with OCaml and F# are the "practical" functional languages. You can get things done out of the gate with any of these languages. You don't have to learn a lot of theory to get things done with Scala, OCaml or F#. With these languages, you can dip your toe in the functional waters without having to take an immediate plunge. Neither of these things is true of Haskell or Erlang.

Scala and F# have the Java and CLR libraries immediately available which is a killer reason to choose either of these languages.

Scala has better OO abstractions than does F# or any other language. Scala seems to have integrated OO and a Type System in a way that no other language has.

Why is your book the right one for people to pick up and learn about Scala?

David I take a very simple approach to Scala. There's very little theory and a whole lot of simple examples and idioms. I've tried to make sure that the code is oriented toward practical users of Java as well as practical users of Ruby. The chapters are short and to the point. More of the code examples can be typed into the REPL (like irb) so the reader can get immediate feedback on the example and the language as a whole.

Why is the JVM a good platform for Scala and FP?

David:

  1. It just works
  2. It's very, very fast
  3. Excellent integration with existing Java libraries
  4. The ability to intermix Java and Scala (and Groovy and JRuby) in a single project
  5. The JVM is everywhere and it's well tuned everywhere

What kinds of problems are a good fit for Scala?

David Heh... everything from simple scripting on up to extremely complex systems. With the exception of Erlang's distributed capabilities and C's native device capabilities, I think that every other problem is well solved with Scala. But, I'm biased. :-)

Design patterns and algorithms look differently when implemented in different languages. Can you give us some examples of elegant patterns or algorithms in Scala?

David A BDD Test:


    object BoxSpec extends Specification {
      "A Box" can {
        "be created from a Option. It is Empty if the option is None" in {
          Box(None) mustBe Empty
        }
        "be created from a Option. It is Full(x) if the option is Some(x)" in {
          Box(Some(1)) must_== Full(1)
        }

A Multi-user web-based chat application:


    case class Messages(m: List[String])

    object ChatServer extends Actor with ListenerManager {
      private var msgs: List[String] = Nil

      protected def createUpdate = Messages(msgs)

      override val highPriority: PartialFunction[Any, Unit] = {
        case s: String =>
          msgs ::= s
          updateListeners()
      }

      this.start
    }

    class Chat extends CometActor with CometListenee {
      private var msgs: List[String] = Nil
      
      def registerWith = ChatServer
      
      override def highPriority = {
        case Messages(m) =>
          msgs = m
          reRender(false)
      }
      
      def render =
      <div>
        <ul>
          {
            msgs.reverse.map(m => <li>{m}</l>>)
          }
        </ul>
        {
          ajaxText("", s => {ChatServer ! s; Noop})
        }
      </div>
    }

A REST API handler:


    case Req(ApiPath :: "statuses" :: 
                        "public_timeline" :: Nil,
           this.method, GetRequest) => publicTimeline

     def publicTimeline(): Box[TwitterResponse] = {
        val statusList =
          Message.findAll(OrderBy(Message.id, 
                          Descending),
                          MaxRows(20)).
            map(msgData _)
        Full(Right(Map("statuses" -> 
                  ("status", statusList) )))
      }

One more very nice piece of code... find all the classes used by <p> tags in an HTML document:


for {p <- x \\ "p"; ca <- p \ "@class"
     c <- ca.text.split(" ")} yield c

What tricks or tools do you suggest someone beginning to read Scala use?

David Don't just read, but use. Open the Scala REPL and start typing. Start playing. Start exploring. Try to understand the actual thing that happens when certain constructs are used. In this way, it's 100% the same as a newbie exploring Ruby. Type a line... see what happens... type another... see what happens. Touch, feel, play.

What are some good Scala code bases to read?

David The Lift utils packages is a nice place to start.

What blogs are good for learning more about Scala?

David

Click here to Tweet this article

No comments: