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




댓글 없음:

댓글 쓰기