Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Python to scala

793 views

Published on

Python to scala. Compare scala to python.

Published in: Software

Python to scala

  1. 1. python to scala
  2. 2. 簡介 ● inwinSTACK ● Openstack contributor ○ Openstack Kolla core member ● kjellytw at gmail dot com ● http://www.blackwhite. tw/
  3. 3. Java to Scala ● Java to Scala
  4. 4. Python ● Object-oriented, ● Imperative ● Dynamic type ● Interpreted languages ● Support shell
  5. 5. Scala ● Functional programming ● Static type ● Object-oriented ● Type inference ● Lazy (non-strict) evaluation ● Compiled languages ● Support shell
  6. 6. python vs scala ● statement, expression. ● a + b => a.__add__ (b) ● f(a,b) => f.__call__ (a,b) ● everything "evaluates" to a value. ● a + b => a.+(2) ● f(a,b) => f.apply(a, b)
  7. 7. variable - python vs scala a = 1 ● The return value of expression is `()`. var a = 1 var a: Int = 1
  8. 8. const - python vs scala ● python doesn’t support const. ● The return value of expression is `()`. val a = 1 val a: Int = 1
  9. 9. lazy ● Not support in native python. (Maybe some library support it. ● Initialization is deferred until it is accessed for the first time ● Check whether the value has already been initialized before a lazy value is accessed.
  10. 10. lazy ● lazy var words = scala.io.Source.fromFile ("/usr/share/dict/words").mkString ● lazy val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map { n => n. _1 + n._2 }
  11. 11. if-else ● statement if a > 5: print(a) else: print() ● expression val x = if(a>5) {1} else 2 val y = if(1!=1) 1 //y == ()
  12. 12. while while a > 5: print(a) a -= 1 ● The return value of expression is `()`. while ( a > 5) { print(a) a -= 1 }
  13. 13. def loop(x: Int, xs: List[Int]): Int = { var max_value = x var rest = xs while (rest != Nil) { if (max_value < rest.head) max_value = rest. head rest = rest.tail } max_value
  14. 14. tail recursion def loop(lst: List[Int], maxValue: Int): Int = lst match { case Nil => maxValue case x :: xs => if (x > maxValue) loop(xs, x) else loop(xs, maxValue) }
  15. 15. tail recursion def max(lst: List[Int]): Int = { lst match { case Nil => 0 case x :: xs => loop(xs, x) } }
  16. 16. tail recursion ● a tail call might lead to the same subroutine being called again later in the call chain. ● a tail recursive function is transformed into a loop by the compiler. ● use `@tailrec`
  17. 17. do while ● Not support do { println(a) a -= 1 while( a > 5)
  18. 18. for
  19. 19. list comprehension vs for yield python scala: the syntax is similar with for.
  20. 20. generator vs stream They are not the same. But they are similar in some case.
  21. 21. function ● You can define many function with the same name. But only the function which is executed in last time will be called. ● Support overloading
  22. 22. scala function def func(a: Int, b: Int) :Unit = { 1 }
  23. 23. scala function 1. def fun = 1 // for pure function 2. def fun() {println(“S”)} # for side effect
  24. 24. function argument ● support variable- length argument, keyworded argumen, default argument. ● support variable- length argument, default argument, call-by-name argument.
  25. 25. variable-length , keyworded , default argument def func(a, b=1, *args, **kwargs): pass def func(a: Int, b: Int = 1, args: Int*) = { 1 }
  26. 26. call-by-name argument ● python doesn’t support call-by-name. ● def mywhile(condition: => Boolean, body: => Unit)
  27. 27. def mywhile(condition: => Boolean, body: => Unit): Int = { def loop(count: Int): Int = { if (condition) { body; loop(count + 1) } else count } loop(0) }
  28. 28. var a = 1 print(mywhile({ a < 5 }, { a += 1 }))
  29. 29. function return ● use `return` if you want to return something. ● if there are no return in function body, it will return `None`. ● avoid to use `return` keyword. ● if there are no return in function body, it will return the value of the last expression
  30. 30. match-case ● python doesn’t support match-case.
  31. 31. match-case x.asInstanceOf[Any] match { case x :: xs => println(x) case (a, b, c) => println(a) case p @ Some(v) if v == 2 => println(p) case x: Int if x != 2 => println(x) case _ => println(“None”) }
  32. 32. class 1. multi inheritance 2. public 3. Not support overloading 1. single inheritance 2. public, protect, private 3. Support overloading
  33. 33. class constructor class My(object): def __init__(self, x): self.x = x self.odd = x%2 ==0 def print_x(self): print(self.x) class My(var x: Int) { var odd = x % 2 ==0 def print_x() { println(x) } }
  34. 34. scala auxiliary constructor class Length(val length: Int) { def this(str: String) { this(str.length) } def this(list: List[Any]) { this(list.length) } } new Length(5) new Length(“Hi”) new Length(List(1,2))
  35. 35. duck typing class Length1(val length: Int) { def this(o: {def length:Int}) { this(o.length) } } ● All thing is duck typing in python. ● scala support duck typing.
  36. 36. scala companion object ● singleton object ● companion object
  37. 37. Singleton object object Main { def sayHi() { println("Hi!"); } }
  38. 38. companion object class Main { def sayHelloWorld() { println("Hello World"); } } object Main { def sayHi() { println("Hi!"); } method,used for instance static method, used for class
  39. 39. How to create instance? class A(object):pass a = A() class A {} val a = new A class B{} object B{def apply() = new B} val bB = B() Python Scala
  40. 40. Type checking and cast 1. isinstance(a, str) 2. issubclass(A, object) 3. a.__class__ 1. "S".isInstanceOf[String] 2. 3. 4. "S".asInstanceOf [String]
  41. 41. Type checking and cast if isinstance(a, int): print(“int”) elif isinstance(a, str): print(“str”) a mtach { case _: Int => println(“int”) case _: String => println(“Str”) }
  42. 42. class inheritance ● Method Resolution Order ● class X(A, B):pass ● X.__mro__ ● single inheritance ● need `override` when overriding ● class X extends Any
  43. 43. scala trait ● trait is like java interface but allows concrete implementations. ● class A extends B with C with D ○ extends + class|trait ○ with + trait
  44. 44. case class ● python doesn’t support case class. ● case class generate the following method: ○ equals ○ apply for companion object . ○ unapply for companion object.
  45. 45. Why we need case class? def Person(object): def __init__(self, name, age): self.name = name self.age = age person = Person(“bill”, 5)
  46. 46. Why we need case class? case class Person(var name:String, var age:Int) val person = Person(“Bill”, 5)
  47. 47. More case calss person match { case Person(name, age) if name == "X" => s"$name,$age" case _ => "Nothing" }
  48. 48. Scala hierarchy
  49. 49. Python hierarchy I don’t care.
  50. 50. package ● folder with `__init__.py` file ● package com.abc. name
  51. 51. import ● the way to use the code in other file. ● use short name
  52. 52. import ● the way to use the code in other file. ● use short name
  53. 53. Implicit ● python doesn’t support implicit. ● Implicit Conversions ○ implicit defwrapString(s: String): WrappedString ● Implicit Parameters ○ implicit val n: Int = 5 ○ def add(x: Int)(implicit y: Int) = x + y ● more thing ...
  54. 54. Scala type parameters ● List[String](); def drop1[A](l: List[A]) = l.tail
  55. 55. Scala type parameters ● List[String](); def drop1[A](l: List[A]) = l.tail ● more thing about: ○ Bounds -> def biophony[T <: Animal] ○ Quantification -> def count(l: List[_]) = l.size ○ Variance
  56. 56. Int ● int, long ● nerver overflow ● Int(32-bit signed) or Long(64-bit signed) or BigInt ● BitInt supports +,%,* ● care for overflow
  57. 57. Boolean ● True and False ● False or True ● not True ● true && false ● true || false ● !true ● short-circuit
  58. 58. String ● no char ● one line string: ○ “string” ○ ‘string’ ● multiline string: ○ “””dddd””” ○ ‘’’ccc’’’ ○ “abcd”[1] ● char => ‘c’ ● string => “c” ● “abcd”(1)
  59. 59. String format ● "%s %d" % ("Hi", 5) ● '{0}'.format('a') ● 'Coordinates: {latitude}'.format (latitude='37.24N',) ● i"{names}" #P0510 ● "%s".format (firstName) ● s"Hello, $name"
  60. 60. List in python vs ArrayBuffer in scala 1. List(1, 2, 3, 4) 2. [1, 2, 3, 4] 3. a[3] 4. a[-1] 5. a[1:-1] 6. a[1:-1:-1] 7. a[1] = 1 1. ArrayBuffer(1,2,3,4) 2. new ArrayBuffer[Int]() 3. a(3) 4. 5. a.slice(1, a.length-1) 6. 7. a(1) = 1
  61. 61. List in python vs ArrayBuffer in scala 1. map(a, lambda x: x+1) 2. b = [i + 1 for i in a if i % 2 ==0] 1. a.map(_ + 1) 2. val b = for(i <- a if i % 2 ==0) yield i + 1
  62. 62. a.map(x:Int => {x + 1}) a.map(x => {x+1}) a.map(x => x+ 1) a.map(_ + 1)
  63. 63. List in python vs ArrayBuffer in scala 1. a.__getitem__ 2. a.__setitem__ 1. a.apply 2. a.update
  64. 64. ArrayBuffer new ArrayBuffer(5) vs ArrayBuffer(5)
  65. 65. Scala List ● Linked list ● Optimal for last-in-first-out (LIFO), stack- like access patterns ● Immutable ● `Nil` means empty list.
  66. 66. Scala List ● List(1, 2, 3) ● 1 :: 2 :: 3 :: Nil ● Nil.::(3).::(2).::(1)
  67. 67. Scala List def max(lst: List[Int]): Int = { lst match { case Nil => 0 case x :: xs => loop(xs, x) } }
  68. 68. Scala Async Future.apply[T](body: ⇒ T)(implicit executor: ExecutionContext): Future[T]
  69. 69. def combined: Future[Int] = async { val future1 = slowCalcFuture val future2 = slowCalcFuture await(future1) + await(future2) }
  70. 70. val future1 = slowCalcFuture val future2 = slowCalcFuture def combined: Future[Int] = for { r1 <- future1 r2 <- future2 } yield r1 + r2
  71. 71. django vs play framework2 ● python web framework ● MVT ● support ORM ● scala/java web framework ● MVC ● support type checking in views.
  72. 72. django class-based views vs play controller def index = Logging { Action { Ok("Hello World") } } class MyView(TemplateView): template_name = "about.html" Play Django
  73. 73. django template vs play view
  74. 74. play view ● type checking ● view as function. ○ views.html.list(List (“1”)) function argument function body call main function list.scala.html
  75. 75. django forms vs play forms
  76. 76. Thank you The slide will update continuously.

×