Showing posts with label Scala. Show all posts
Showing posts with label Scala. Show all posts

Monday, July 16, 2012

'Programming in Scala' book now FREE


If you're looking to learn Scala or looking to broaden your knowledge thereof, you'll be pleased to know that it's just been announced that the first edition of 'Programming in Scala' by Martin Odersky (the creator of Scala), Lex Spoon, and Bill Venners is now FREE online in HTML format.

How to learn ScalaYou will learn a lot about Scala simply by reading this book from cover to cover. You can learn Scala faster and more thoroughly, though, if you do a few extra things.First of all, you can take advantage of the many program examples included in the book. Typing them in yourself is a way to force your mind through each line of code. Trying variations is a way to make them more fun and to make sure you really understand how they work.Second, keep in touch with the numerous online forums. That way, you and other Scala enthusiasts can help each other. There are numerous mailing lists, discussion forums, a chat room, a wiki, and multiple Scala-specific article feeds. Take some time to find ones that fit your information needs. You will spend a lot less time stuck on little problems, so you can spend your time on deeper, more important questions.Finally, once you have read enough, take on a programming project of your own. Work on a small program from scratch, or develop an add-in to a larger program. You can only go so far by reading.


Here's the announcement:
http://groups.google.com/group/scala-announce/browse_thread/thread/502c7d5a386e357f

Here's the online version:
http://www.artima.com/pins1ed/
read more...

Redis key-value database


Redis is a key-value database. It is similar to memcached but the dataset is not volatile, and values can be strings, exactly like in memcached, but also lists and sets with atomic operations to push/pop elements.
In order to be very fast but at the same time persistent the whole dataset is taken in memory and from time to time and/or when a number of changes to the dataset are performed it is written asynchronously on disk. You may lost the last few queries that is acceptable in many applications but it is as fast as an in memory DB (Redis supports non-blocking master-slave replication in order to solve this problem by redundancy).
Compression and other interesting features are a work in progress. Redis is written in ANSI C and works in most POSIX systems like Linux, *BSD, Mac OS X, and so on. Redis is free software released under the very liberal BSD license.
It is possible to think at Redis as a data structures server, it is not just another key-value DB, see all the commands supported by Redis to get the first feeling. Redis supports operations like atomic push and pop of elements on lists, taking ranges of elements from this lists at once, trimming of lists, server-side intersections of sets and even sorting data! To show our points we wrote a simple Twitter clone with PHP + Redis: it's a very simple but still a real world example of web application, the article explains step by step how to write scalable applications with Redis.
Supported languages: PHP, Java, Ruby, Python, Perl, Tcl, Erlang, Scala, Lua etc.

Devis's blog
read more...

Operator Overloading: Scala vs. C++

When I was reading "Programming in Scala" to learn the language, I came across some elements that reminded me of things that were in C++, but were left out of Java because they were seen to be dangerous and caused problems. One of these is operator overloading. This blog post is largely in response to a post called "'Operator Overloading' in Scala". That post gives a good description of the basics so I won't repeat it here. I mainly want to write about something I feel is missed, that is the reason why what Scala does is different from C++, and why Scala's version is less dangerous.

The problem people generally associate with operator overloading is that you can produce unreadable and confusing code. Something like overloading + to do multiplication. I think this is a poor description of the problem. You can write unreadable code without operator overloading as well. For example, you could write a Java method called add which does multiplication. No reasonable developer would do that, and allowing operator overloading doesn't suddenly make people stupid. The real problem with C++ operator overloading is that it is limited to normal operator names. To see why this matters, imagine a situation in Java where you were restricted to method names like "add", "subtract", "multiply", and "divide". Now you implement a vector class that needs methods like dot product and cross product. What do you do?

In C++ if you have any operations that are similar to mathematical operations, the language basically seduces you into using normal operators for them. It is easier to type * than to have a full method call. Perhaps * isn't a perfect fit, but it is the best you can use and you think it will make code easier to work with. The problem is that when other people use the code, the * looks just like any other multiplication and it isn't immediately obvious it is doing something different.

This is where Scala is a major improvement. Operators aren't limited to standard names. They can use any combination of operator symbol characters. So if you had the vector class mentioned above you could use *+* for dot product and *** for cross product. I won't argue those are great names. Indeed, I would probably argue against them. However, when another programmer sees a *+* b in code, he/she will know this is not normal multiplication, and know something needs to be looked up.

Scala collections, in my opinion, make good use of this. For example, consider a sequence called stuff and a single value called v. You can prepend and append to stuff with a +: stuff and stuff :+ a respectively. IfmoreStuff is another sequence, then stuff ++ moreStuff appends the two sequences. This type of usage is highly readable, but wouldn't be possible in the C++ model.

One of the great things about the Scala syntax is that these symbolic operators are not special cases. Any method that takes zero or one arguments can be used in operator notation. So instead of using *+* and ***, you could simply use dot and cross. In the code you could then write a dot b or a cross b. The only drawback to this approach is that the dot and cross methods will have lower precedence than +. So the expression c + a cross b will be seen as (c + a) cross b instead of c + (a cross b). If you use ***, the normal precedence rules will give you the latter form, which is what is normally expected in vector math.


In summary, I think that the creators of Java were wise to not follow in the footsteps of C++ with operator overloading. It really does push programmers into doing some silly things. However, Java was probably an overreaction. With the approach taken in Scala, we get a best of both worlds. You can have operators when you really have mathematical operations and you get the simplified, infix operator syntax. However, you aren't restricted to basic operator names, or even symbolic operators in order to use infix notation.


read more...

Friday, July 6, 2012

Install Scala on MAC OS X ( LION )

Hello there, in this post I will share how to install Scala on your Mac Lion. First thing you need to do is download the latest Scala compiler. Click here and download the .tgz compiler package. I recommend downloading the.tgz file rather than .jar.

When the download completed, unpack and move it to your user home folder. For example, "/Users/your_user/". Once you moved it to the user's home folder, now create or modify your ".profile" files in your home folder. Open the Terminal and use Vim or Nano to add the line below to the end of file.
export PATH="/Users/your_user/scala/bin:$PATH"
Save and close the modified file. Now apply the changes using this command.
source .profile
Close the Terminal and reopen it to check the result. To verify whether the Scala working well, in the Terminal type in “Scala” and you should see the output like the quote below.
 
iMac-my:~ ogonbat$ scala
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
Type in expressions to have them evaluated.
Type :help for more information.

scala>


read more...

Monday, July 2, 2012

How to install Scala on Debian/Ubuntu (Scala 2.9.0.1, 2.8.1)

Update: Scala 2.9.0.1 (hotfixes to 2.9.0, released on May 12) was released on May 25, 2011. In this tip you can find a way how to install it (and older version - 2.8.1) onto yours Ubuntu/Debian box.
Ubuntu default apt repository gives us option to install only scala-2.7.7, but if you want to use latest version of scala (2.9.0.1 2.8.1 to date when this tip was written), so all what we need to do is this actions:

$ wget http://www.scala-lang.org/downloads/distrib/files/scala-2.9.0.1.tgz
$ tar zxf scala-2.9.0.1.tgz
$ sudo mv scala-2.9.0.1 /usr/share/scala

But if you need to install older (2.8.1) version of scala you need to run next commands:
 
$ wget http://www.scala-lang.org/downloads/distrib/files/scala-2.8.1.final.tgz
$ tar zxf scala-2.8.1.final.tgz
$ sudo mv scala-2.8.1.final /usr/share/scala


Ok, now you we need to make a few links to scala binary, scalac (scala compiler), fsc (fast scala compiler) and others scala executables:
$ sudo ln -s /usr/share/scala/bin/scala /usr/bin/scala
$ sudo ln -s /usr/share/scala/bin/scalac /usr/bin/scalac
$ sudo ln -s /usr/share/scala/bin/fsc /usr/bin/fsc
$ sudo ln -s /usr/share/scala/bin/sbaz /usr/bin/sbaz
$ sudo ln -s /usr/share/scala/bin/sbaz-setup /usr/bin/sbaz-setup
$ sudo ln -s /usr/share/scala/bin/scaladoc /usr/bin/scaladoc
$ sudo ln -s /usr/share/scala/bin/scalap /usr/bin/scalap

And how to uninstall (for both versions of scala):

$ sudo rm -rf /usr/share/scala /usr/bin/scala /usr/bin/scalac /usr/bin/fsc /usr/bin/sbaz /usr/bin/sbaz-setup /usr/bin/scaladoc /usr/bin/scalap
read more...

Thursday, May 17, 2012

Scala Examples - Advanced


SourceDescription
addressbook.scalaAddress book to XHTML code (see also XML Processing)
callccInterpreter.scalaInterpreter with continuations using monads
fors.scalafor comprehensions (see also Sequence Comprehensions)
gadts.scalaGeneralised algebraic data types
lazyEvaluation.scalaLazy evaluation
message.scalaActors (see also Actors for Scala)
patterns.scalaPattern matching using case classes (see also Case Classes)
extractorPatterns.scalaPattern matching using extractors - a flexible way of matching objects with patterns
pingpong.scalaActors (see also Actors for Scala)
properties.scalaProperties
random.scalaClient/server application using Java sockets
simpleInterpreter.scalaSimple interpreter using monads
sort.scalaRecursive quicksort algorithm (imperative solution, see also Nested Functions)
sort1.scalaRecursive quicksort algorithm (functional solution)
timeofday.scalaProperties (see example 1 in § 4.2 of the Scala Language Specification)
vectors.scalaVector operations using views (see also Views)
brainf_ck.scalaA small Brainf*ck interpreter


To compile and run on Windows one of the above Scala programs, let's say sort.scala, we can simply proceed as follows:
> mkdir classes
> scalac -d classes %SCALA_HOME%\doc\scala-devel\scala\examples\sort.scala
> scala -cp classes examples.sort
[6,2,8,5,1]
[1,2,5,6,8]
The name of the Scala executable is examples.sort where examples is the name of the package containing the sortobject. Running the test on a Unix system is very much similar, except for the use of slashes instead of backslashes, and a different specification of the Scala home directory.

Other Scala examples

Finally, the following ressources contain Scala examples as well:
  • The Scala distribution contains a directory examples with other source examples.
  • The document Scala By Example (about 150 pages, available in PDF format) contains more advanced Scala examples.
  • The Scala Wiki contains many other code examples.

scala-lang.org
read more...

Wednesday, May 16, 2012

Scala Nugget – Pattern matching and Lists


I was whining recently about how my scala-code is java in poor disguise. I started reading the scala by example pdf that also comes with the scala installation. I just read some interesting things about lists and pattern-matching that gave me an idea how to “scalafy” the following scjava-code:
  def importResource(name:String, resource:Resource):Unit = {
    log.debug("importing " + name + " into " + root)
    val path = pathOf(name)
    createResource(path.toList)(resource)
  }

  private def createResource(nodes:List[String])(resource:Resource) =  {
    val directory = nodes.dropRight(1).foldLeft(root)((directory, name) => {
      if(name.equals("")) {
        directory
      }
      else {
        val directoryOption:Option[AbstractDirectory] = directory.getDirectory(name)
        directoryOption.getOrElse({
          val subDir = directory.createDirectory(name) match {
                         case result:AbstractDirectory => result
                       }
          directory.add(subDir)
          subDir
        })
      }
    })
    directory.createIfNewer(nodes.last, _:Resource)
  }
If it’s not crystal clear to you what the code does. Here is an overview:
  • The first method takes a name and a resource
  • The name is split up into it’s path-elements
  • The path is passed to the createResource method that will create all directories that does not yet exist on the way to the resource and finally return a function that takes a resource as input and creates it in the already given directory.
A big issue I have with the code is the createResource-method. It simply is very hard to name it. createAllDirectoriesAndReturnResourceCreatingMethod would illustrate better how smelly that method really is. I have an idea on how to refactor this with scalas pattern matching. This is the new version (after some red/green bar cycles):
  def importResource(name:String, resource:Resource):Unit = {
    log.debug("importing " + name + " into " + root)
    val path = pathOf(name)
    createResource(path.toList, root, resource)
  }

  private def createResource(nodes:List[String],
                             directory:AbstractDirectory,
                             resource:Resource) {
    nodes match {
      case head :: Nil => directory.createIfNewer(head, resource)
      case "" :: tail => createResource(tail, directory, resource)
      case head :: tail => {
        val subDir = directory.getDirectory(head).getOrElse {
          val result = directory.createDirectory(head) match {
                                   case dir:AbstractDirectory => dir
                                 }
          directory.add(result)
          result}
        createResource(tail, subDir, resource)
      }
      case nil =>
    }
  }
The first thing that strikes me about the second version is the unbalance between the different cases. Thehead :: tail case is not exactly a one-liner… but it should be. This smells like feature envy. We could ask the directory to getOrCreateDirectory and it would read much better. But that is another refactoring. First let’s go through this one:
One thing I did not first get in scala is how you can iterate through lists using pattern-matching. In order to get how that works it is important to realise one thing about scalas lists:
List(“a”, “b”, “c”, “d”)
is equivalent to
“a” ::(“b” ::(“c” ::(“d” ::(Nil))))
which due to the right associativityness of :: is equivalent to:
“a” :: “b” :: “c” :: “d” :: Nil
Or plain english: Lists are not flat structures, lists are recursive structures. What that means in practical terms is that given any element in the list it is very easy to split the list at that element into head (the current element) and tail (the rest of the elements.
For instance, given the element “b” above, head will be “b” and tail will be “c” :: “d” :: Nil.
Ok, not that hard. Now to the cool part: The :: operator is a case class which in short means that it can be used in pattern matching:
“a” :: “b” :: “c” :: Nil match { case h :: t => println(head +” -> ” +tail); …}
will assign “a” to the variable h and “b” :: “c” :: nil to the variable t
We can now understand the cases above. In pseudocode:
  private def createResource(nodes:List[String],
                             directory:AbstractDirectory,
                             resource:Resource) {
    nodes match {
      case head :: Nil =>  //the last element of the list, create the resource using head as a name
      case ""   :: tail => // special case, an empty directory name. Skip to the next name:
                           // createResource(tail, directory, resource)
      case head :: tail => //head will be a directory-name that we use to get or create the 
                           //nextDirectory that is used with tail to call ourselves recursively:
                           // createResource(tail, nextDirectory, resource)
      case nil => //no more elements to traverse
    }
  }
I’m far from done with the refactoring. I want to get rid of the special case of “” to begin with and as mentioned above remove some feature-envy but I think that the cases are more readable than the original code. At least in terms of where the problems lie in terms of special cases and bloated cases. Of course, it’s just an opinion and I reserve the right to change my mind tomorrow :)

Written by johlrogge
read more...

Scala tips, tricks, and info


Here are a collection of tips, tricks, and general information I have gleaned from using Scala for a while. These tips apply to Scala 2.7.3

Case classes
You can define a case class like so:

case class Foo(x: Int)
 


A case class definition, such as case class Foo(x: Int) does the following things:
  • Defines a class named Foo.
  • Exposes a getter, x.
  • Defines a case class constructor function, also named Foo.


The case keyword is merely a convenience; you can achieve the same result by writing this:

class Foo(val x: Int)
def Foo(x: Int) = new Foo(x)
 


Don't confuse case classes and objects. If you define an object, and you want to instantiate it via ObjectName(), you must write an apply method in your object.

Pattern matching gotchas
A common mistake that newbies make is that Scala expects constants to be in uppercase. If you try to match a constant in uppercase, Scala will use that constant. If you try to match a constant that is in lowercase, Scala will think you want to bind a new variable to that identifier, resulting in unexpected behavior. Take a look at the following example:

// Binds a new variable to foo:
// Don't do this!
match {
  case foo => "yes"
  case _ => "no" /* Unreachable code */
}

// Uses existing variable foo:
// Do this if you must.
match {
  case `foo` => "yes"
  case _ => "no"
}

// Uses existing variable FOO:
// Do this because it's the best.
match {
  case FOO => "yes"
  case _ => "no"
}
 


Synchronized collections (or adding other traits)

val map = new HashMap[String, Int] with SynchronizedMap[String, Int]
 


Multidimensional maps

case class MulMap[K1, K2, V] {
  val wrapped = new scala.collection.mutable.HashMap[(K1, K2), V]
  def update(k1: K1, k2: K2, v: V) = wrapped.put((k1, k2), v)
  def apply(k1: K1, k2: K2) = wrapped((k1, k2))
}

val map = MulMap[String, String, Int]
map("apple""orange") = 4
 


Multidimensional arrays

new Array[Array[Boolean]](width, height)
 

A shorter way to write list literals

def L[T](xs: T*) = List(xs: _*)
L(123)
// OR
val L = List
L(123)
// OR
import scala.{List=>L}
L(123)
 


Differences between val, lazy val and def
  • vals are only evaluated the first time they are declared.
  • lazy vals are only evaluated the first time they are referenced.
  • defs are evaluated each time they are referenced.
read more...

Getting started with Scala using SBT


One of my biggest gripes with Java (and all the languages that run on the JVM) is getting my project setup and building it. Maven is not my favorite, and ant..well..I don’t like it either. Fortunately, if you want to start a new project in Scala, there is a great build tool available that takes a lot of the pain out of project management and building – SBT, simple-build-tool.
sbt is a simple build tool for Scala projects that aims to do the basics well. It requires Java 1.5 or later.

Installing SBT

I’m using Mac OS X, but the following instructions should be pretty much the same on any Unix based OS.
You can find the latest version of SBT here.
1
2
3
4
5
cd ~
wget http://simple-build-tool.googlecode.com/files/sbt-launcher-0.5.6.jar
sudo mv sbt-launcher-0.5.6.jar /usr/local/bin/sbt-launcher.jar
echo "java -Xmx512M -jar /usr/local/bin/sbt-launcher.jar \"\$@\"" | sudo tee /usr/local/bin/sbt
sudo chmod +x /usr/local/bin/sbt
This will install the SBT jar and create a script called sbt that will allow you to run the sbt jar.
Just type sbt and press enter, and you now have access to sbt.
1
2
$ sbt
Project does not exist, create new project? (y/N/s) : n

Creating a new Scala project

Now we will create a Hello World Scala project with SBT.
1
2
mkdir hello_scala
cd hello_scala
Running the sbt command in a directory where there is no project will prompt you to create one.
1
sbt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Project does not exist, create new project? (y/N/s) : y
Name: Hello, Scala!
Organization []: 
Version [1.0]: 
Scala version [2.7.7]: 
sbt version [0.5.6]: 
:: retrieving :: sbt#boot
    confs: [default]
    2 artifacts copied, 0 already retrieved (9911kB/72ms)
:: retrieving :: sbt#boot
    confs: [default]
    3 artifacts copied, 0 already retrieved (3409kB/15ms)
[success] Successfully initialized directory structure.
[info] Building project Hello, Scala! 1.0 using sbt.DefaultProject
[info]    with sbt 0.5.6 and Scala 2.7.7
[success] Build completed successfully.
[info] 
[info] Total build time: 0 s
Awesome. It handles all the Scala dependencies for us! Now let’s create a file that contains our Hello, Scala example.
Below is the directory structure of an SBT project.
1
2
ls
lib project src

Creating our HelloScala sources and running

Now we are going to create our main file, HelloScala.scala
src/main/scala/HelloScala.scala
1
2
3
4
5
object HelloScala {
  def main(args: Array[String]) {
    println("Hello, Scala!")
  }
}
And now we can build and run it by just issuing the following:
1
sbt run
And the output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[info] Building project Hello, Scala! 1.0 using sbt.DefaultProject
[info]    with sbt 0.5.6 and Scala 2.7.7
[info] 
[info] == compile ==
[info]   Source analysis: 0 new/modified, 0 indirectly invalidated, 0 removed.
[info] Compiling main sources...
[info] Nothing to compile.
[info]   Post-analysis: 2 classes.
[info] == compile ==
[info] 
[info] == copy-resources ==
[info] == copy-resources ==
[info] 
[info] == run ==
[info] Running HelloScala ...
Hello, Scala!
[info] == run ==
[success] Successful.
[info] 
[info] Total time: 0 s
[success] Build completed successfully.
[info] 
[info] Total build time: 1 s
And that’s it. Setting up a new Scala project with SBT is painless. In the next part I will talk about managing dependencies and how SBT makes this also very easy.
You can read a lot more about SBT by checking out their wiki.
Update 09/18/2011 – 
If you are on a Mac, its probably easier to install sbt this way:
1
brew install sbt
The above command requires homebrew, a package manager for OS X. Get it here: https://github.com/mxcl/homebrew


chrismoos.com
read more...