2009년 10월 15일 목요일

Scala for Python Programmers - Traits? what is it?

Before diving into real-OO things in Scala, I believe that you should know what are traits. In Python there is no such thing, but if it'd exist then I am sure you'd love to use.

There are two things to compate with traits (1) Multiple Inheritance (2) Mixin

Python supports limited Multiple Inheritance, oftenly multiple inheritance is criticized for many reasons.

class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>

Above examples shows multiple inheritance thingy in Python. But why its bad?  Semantic ambiguity,  Not being able to explicitly inherit multiple times from a single class and Order of inheritance changing class semantics. In general Multiple inheritance may produce wrong output in some cases. That's why Mixin is invented?

Some says Multiple Inheritence is an Evil, While some says it is not, IMO it is upto you how you do it. In compex circumstances it may turn out to be an evil. Mix-in is very similar to Abstract Base Classes, Mixin class is to be inherited by subclass and it donot get instantized.

>>> class MixCounter(object):
...     count_from = 0
...     def next(self):
...             return self.count_from + 1
...
>>> class CountFrom10(MixCounter):
...     count_from = 10
...
>>> CountFrom10().next()
11


In Scala you'd do something like

scala> abstract class MixCounter {
     | val count_from = 0
     | def next():Int = { return count_from+1 }
     | }
defined class MixCounter

scala> class CountFrom10 extends MixCounter {
     | override val count_from = 10
     | }
defined class CountFrom10

scala> val a= new CountFrom10()
a: CountFrom10 = CountFrom10@1da366c

scala> a.next()
res4: Int = 11

But Scala also offer's traits. Traits are very similar to Mixin or Abstract classes but they may also include definations for class methods. In principal traits doesnt mix classes e.g if you run trait version of above example

scala> trait CountNumber {
     | val count_from = 0
     | def next():Int = { return count_from + 1 }
     | }
defined trait CountNumber

scala> class CountFrom10 extends CountNumber {
     | override val count_from = 10
     | }
defined class CountFrom10

scala> val a = new CountFrom10()
a: CountFrom10 = CountFrom10@18590c5

scala> a.next()


So what you think what should be the result? 11 or 1? No it's not 11 .. it's 1

res6: Int = 1

So, you see traits is very different from mix-in though it's quite resemble. It looks that mix-in is actually mix-in one class but trait does it bidrectionally. Now consider following example.

scala> trait EvenOddTeller {
     | def is_even(x: Int): Boolean
     | def is_odd(x: Int): Boolean = !is_even(x)
     | }
defined trait EvenOddTeller

scala> class Number extends EvenOddTeller {
     | def is_even(num:Int):Boolean = { return num%2==0 }
     | }

scala> val a= new Number()
a: Number = Number@1d15a18

scala> a.is_even(10)
res7: Boolean = true

scala> a.is_odd(10)
res8: Boolean = false

scala> a.is_odd(11)
res9: Boolean = true


In scala traits you have to define all methods which are just declated in trait in your subclass. In short Scala Traits provides a safe mix-in mechanism with full re-usability.

scala> trait RestResource {
     | def response():String
     | def json():String = { return "{rsp:%d}".format(response) }
     | def xml():String = { return "<rsp>%s</rsp>".format(response) }
     | }
defined trait RestResource

scala> class Resource(val inp:String) extends RestResource {
     | val input: String = inp
     | def response() = { return input }
     | }

scala> new Resource("Hello World") xml
res15: String = <rsp>Hello World</rsp>


There are many place in development traits are very useful.









2009년 10월 14일 수요일

Scala for Python Programmers - Functions and Methods and List

In previous post, I gave an idea about how to write simple function including lambda so called anonymous functions. In this post, I'll compare Python and Scala functions

First off! In scala Operators are methods i.e +,- etc are methods so if you do 1+2 or 1 .+(2) it's same and now you might think what the hell! Yes its confusing but revolutary isn't it? So in python you do something like

>>> a = [1,2,3,4,5]
>>> a.reverse()
>>> print a
[5, 4, 3, 2, 1]


In scala you would do like

scala> List(1,2,3,4).reverse
res8: List[Int] = List(4, 3, 2, 1)


or

scala> List(1,2,3,4) reverse
res9: List[Int] = List(4, 3, 2, 1)


Thats correct! a method which does not accept any argument can be called without parantesis and a method can be called without do e.g

scala> List(1, 2, 3, 4) foreach println
1
2
3
4

Something similar to method chaning but more readable, though hard to imagine something like this. Above is equivalent to

scala> List(1, 2, 3, 4).foreach((i: Int) => println(i))

Or in python world its

>>> for i in [1,2,3,4]:
...     print i


So remember Operators are methods, Methods without argument should be called without parentheses and you can call methods with space instead of dot and method chaning is allowed.

In functional programming most of the time you deal with list so imo it's very necessary to know basic list operations in scala.

:: method (it appends an element to List on top)

scala> var a = List(1,2,3,4,5)
a: List[Int] = List(1, 2, 3, 4, 5)

scala> 0 :: a
res17: List[Int] = List(0, 1, 2, 3, 4, 5)

In python it'd would be

>>> a = [1,2,3,4,5]
>>> a.insert(0,0)
>>> print a
[0, 1, 2, 3, 4, 5]

In simple worlds :: is a List method which takes anything and add to head of list i.e

scala> a.::(0)
res20: List[Int] = List(0, 1, 2, 3, 4, 5)


In Scala any method which ends with : binds  to the right not to the left.

++ method (it concat two lists)

scala> var a = List(1,2,3,4,5)
scala> a ++ List('a', 'b')
res21: List[AnyVal] = List(1, 2, 3, 4, 5, a, b)


In Python you can use +
>>> [1,2,3] + ['a', 'b']
[1, 2, 3, 'a', 'b']


You can get list of all List methods here it worth reading. Remember mastering FP requires mastering List.
http://www.scala-lang.org/docu/files/api/scala/List.html




Google Wave - XMMP on web?

Google Wave - Google's upcoming xmmp based tool for real-time communication. Beside it's UI i didn't find anything interesting in it. However, Google is claiming its a big leap in intenet communication it's going to replace emails. Uhmm! Well I am not an orthodox, I love new technology pondering around but I hardly see that it'd replace emails.

What happened when Instant Messaging arrives? It provide similar communication process like email, though it has been an integrated part of intenet communication but it failed to replace email. Why? Because People are not always online (I assume even IM provides offline messaging), its hard to use by older generation (specially those who do not know computers well) and its not email (People loves To, Subject, Body Trilogy).

Google wave is just an IM tool with web interface. It stores your messages (I'd call conversations). Bots or Agents are also presents in IM world. IN wave world they are same. However there have been effort to simplify development and hosting process for these hosts by Google's AppEngine XMMP.

In simple world 90% of Google Wave is XMMP communication which we are already doing via Jabber. At least I am not excited about Google wave than Google Voice.




2009년 10월 12일 월요일

Scala for Python Programmers

You might be a Python Ninja, but mastering Scala would be hard if you'r scared of real-OO languages. As "Cal Henderson" mentioned last year at djangocon: "Python is for Hippies who scared of real-OO languages". To some extent its true because Python gives you an illusion that you are doing everything in object but most of the time you'r just iterating in script. However, if you knows what exactly are classes and objects then you can write better code.

I truely hates Java and JVM like languages why? because it slow down my laptop else? because they got bloody eclipse which is not much different than Visual Studio .NET 200x and lastly? I am not wearing suits. I hate JVM languages as much as I hate Ruby. But sometime you come across a turning point and ask yourself, what you do? hmm.. I writes program in Python .. so does everyone else on planet earth and then you think probabaly I should learn another language .. then you prepare a list C++, Java, C#, smaltalk, Ruby, Groovy, clojure, Lisp, Erlang and Scala.  And eventually scala seduce you with JVM, CLR, Scalability, industrial need and Ha! no one actually knows Scala. But wait its JVM language? hell yes but I have mastered art of programming and I can learn anything decent( I got this illusion by writing cutting edge programs in Python in last few years).

All you need is Google "Scala tutorial", you install Scala compiler and write your HelloWorld.scala - so cool :)

object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}

But its not really cool as you digg in you see competely different world and you ask yourself, is it worth learning scala? I can do this in Python in 2 lines. In short all you need to learn scala is Patience if you'r a Python or Ruby or Smalltalk programmer.

Damn! why the hell Scala guys made it too hard, they couldn't do this in Python like syntaxs? Please do not ask me this question ask EPFL guys. Please do not lost yout Patience while reading and learning scala programs.

Python, Ruby, Groovy, Smalltalk and Javascript is Dynamically Typed languages that makes them more productive than Scala which is a Staically Typed language. Difference is in Python you do something like this

>>> name = "Jon"
>>> print name
Jon
>>> name = 1
>>> print name
1

A value is bound to the Variable and type is bound to the value. In static typing type is bound to the Variable.

scala> var name = "Jon"
name: java.lang.String = Jon

scala> name = 1
<console>:5: error: type mismatch;
 found   : Int(1)
 required: java.lang.String
       name =1

So Remember, Scala = Statically Type language just like C++ which you might have learnt in school. I know it sucks but Scala guys should have some reason for it. Remember be Patient and try some meditation ;)

If you are a Python programmer then you might be assuming that you knows FP (Functional Programming) but I would reject your claim unless you know Lisp or Erlang or Scala's Actor. FP is just not about operation on list. It's more about
communicate by passing messages between concurrent, autonomous processes both Lisp and Erlang does that. To ease this thing FP often go with immutable state, i.e you cannot modify value of a variable. The coolest thing about Scala is that it support fully FP using Actors library and it also allows mutable and immutable type of variables. So, if you think Erlang is pretty cool think again in scala it is much more easier to write inter-process programs. BTW Python is lame enough to be not compared in this section.

//Import Pretty similar to Python where _ resemblance * e.g from scala.actors.Actor import *
scala> import scala.actors.Actor._
import scala.actors.Actor._

scala> import scala.actors.Actor
import scala.actors.Actor


// Define a class Acting, here Unit resemble Void or None in Python
scala> class Acting extends Actor {
     | def act() {
     | loop {
     | receive {
     | case 1 => println("yes")
     | case 0 => println("no")
     | }
     | }
     | }
     | }
defined class Acting

//create acting object
scala> var ac = new Acting()
ac: Acting = Acting@c42b5 //
Acting@node_name

//start acting
scala> ac.start
res4: scala.actors.Actor = Acting@c42b5

//send value to acting object
scala> ac ! 1
yes


scala> ac ! 0
no



It's Actor library allows you to write concurrent FP.

If you loves python mixin composition in classes then You have Scala Traits. It is much similar to Python modules.

In python you write anon function or so called lambda functions like

>>> g = lambda x: x * x
>>> g(3)
9


But in Scala you do

scala> var g = (x: Int) => x * x
g: (Int) => Int = <function>

scala> g(3)
res46: Int = 9


"=>" is oftenly used for anon functions in scala. It can be re-written as:

>>> def g(x):
>>>    return x*x


and in scala

scala> def g(x: Int): Int = x * x

Lets write another Python and Scala Program that would conver list of strings into Upper case: Python

>>> a = ['Hello', 'World', 'Python', 'Scala']
>>> up = [item.upper() for item in a]
>>> print up
['HELLO', 'WORLD', 'PYTHON', 'SCALA']


In Scala:

scala> var a = List("Hello", "World", "Python", "Scala")
a: List[java.lang.String] = List(Hello, World, Python, Scala)

scala> var upp = for(x <- a) yield x.toUpperCase
upp: List[java.lang.String] = List(HELLO, WORLD, PYTHON, SCALA)


See how Scala force you to use generators :)

Let me summarize:

1. Be Patient if you'r a Python, Ruby or smalltalk developer. Scala would require lots of Patience.
2. Scala is a Statically typed language. Watch your types.
3. Scala Actor library allows you to write server-client, concurrent Programs just like twisted and stackless do.
4. Scala is fully Functional Programming language like Lisp and Erlang.
5. => is used for anon functions (lambda in python terminology) and = is used in writing proper functions.