Programmierparadigmen und Sprachen Scalast.inf.tu-dresden.de/files/teaching/ss09/PS09/henke... ·...
Transcript of Programmierparadigmen und Sprachen Scalast.inf.tu-dresden.de/files/teaching/ss09/PS09/henke... ·...
Fakultät Informatik – Institut für Software- und Multimediatechnik – Professur Softwaretechnologie
Programmierparadigmen und Sprachen
ScalaScala
Paul HenkeDresden, 07.05.2009
GliederungGliederung
• Hello WorldHello World
• Scala?
• Features
• Demo
TU Dresden, 07.05.2009 Scala Folie 2 von 21
Hello WorldHello World
object HelloWorld { def main(args: Array[String]) {
println("Hello, world!") }
}
TU Dresden, 07.05.2009 Scala Folie 3 von 21
Scala?Scala?
• „Scalable Language“„Scalable Language
• wird von Martin Odersky (EPFL, Schweiz) seit 2001 entworfen und entwickelt
• statisch getypte Multiparadigmensprache
• verknüpft Objektorientierte Programmierung mit Funktionaler
• läuft auf der JVM sowie in .Net
• vollständig in die jeweilige Umgebung integriertvollständig in die jeweilige Umgebung integriert
• aktuelle Version 2.7.4
TU Dresden, 07.05.2009 Scala Folie 4 von 21
Features
• Klassen• Einfach Vererbung• Mixins (durch Traits)• Alles wird als Objekt behandelt
T I f• Type Inference• XML als nativer Datentyp• Schönfinkeln• Partial ApplicationPartial Application• First Class und Higher Order Functions• Closures• Structural Typing• Pattern Matching• Tupel• Actors und Messages
TU Dresden, 11.05.2009 Scala Folie 5 von 21
Syntax
• Semikolons unnötig• keine Operatoren• Methoden können Infix geschrieben werden• Klammern können bei Methoden mit maximal einem Parameter weggelassen
werden1 + 2 statt 1.+(2)
• geeignet für Domain Specific Languages (durch viele Freiheiten in der Syntax)• z.B. ScalaTest Framework
collection should contain element 1.0result should be >= 0
TU Dresden, 07.05.2009 Scala Folie 6 von 21
Klassenhierarchie
TU Dresden, 07.05.2009 Scala Folie 7 von 21
KlassenKlassen
class Person(name:String, age:Int) {def Name:String = namedef Age:Int = agevar city:String = ""
def sayHi { println("Hi") }override def toString():String = name + " (" + age + ")"
}}var p:Person = new Person("Horst", 20)println(p.Name) // Horstprintln(p) // Horst (20)
p.sayHi() // Hip.city = "Dresden"
TU Dresden, 07.05.2009 Scala Folie 8 von 21
Singletons Objects
• es gibt keinen static Modifier
object Math {def PI:Double = 3.14159 def pow(b:Long,e:Long) = {}def sin(a:Double) = {}def cos(a:Double) = {}def cos(a:Double) = {}/* .... */
}
println(Math.pow(2,8)) // 256
TU Dresden, 07.05.2009 Scala Folie 9 von 21
Type Inference
• auf Typangaben kann ich den meisten Fällen verzichtet werden
• Variablenvar x = 5 // x:Intvar y = "Scala“ // y:Stringx = "ist toll" // type mismatchvar z = x * 10 // z:Intvar z = x 10 // z:Int
• Rückgabetyp von Funktionendef add(x:Float, y:Float) = { // add(Float, Float):Float
x+y
}
TU Dresden, 07.05.2009 Scala Folie 10 von 21
Traits
• abstrakter Typabstrakter Typ• ähnlich wie Java Interfaces bzw abstrakte Klassen• Mixin Composition -> „Mehrfach Vererbung“
trait Occupation {var occupation = ""override def toString = super toString + "(" + occupation + ")"override def toString = super.toString + "(" + occupation + ")"
}trait Status {
var status = ""override def toString = super.toString + "(" + status + ")"
}
TU Dresden, 11.05.2009 Scala Folie 11 von 21
Traits
class BetterPerson(n:String, a:Int) extends Person(n,a) withOccupation with Status
l b B tt P ("Ali " 25)val bp = new BetterPerson("Alice", 25)bp.occupation = "Student"; bp.status = "Married"println(bp) // Alice (25)(Student)(Married)println(bp) // Alice (25)(Student)(Married)
TU Dresden, 11.05.2009 Scala Folie 12 von 21
Traits
trait Ord[T] {def < (that: T): Booleandef <=(that: T): Boolean = (this < that) || (this == that)def > (that: T): Boolean = !(this <= that)def > (that: T): Boolean = !(this <= that)def >=(that: T): Boolean = !(this < that)
}class Rational(n: Int, d: Int) extends Ord[Rational] {
/* … */def <(that: Rational) = numer * denom > that.numer * that.denom
}var r1 = new Rational(7,5)var r2 = new Rational(13,7)
println(r1 > r2) // true
TU Dresden, 11.05.2009 Scala Folie 13 von 21
First Class Functions
• Funktionen • sind auch Objekte• haben einen Typ• können Variablen zugewiesen werden
val printHi:() => Unit = () => println("hi")printHi() // "hi"printHi() // hi
val return5:() => Int = () => 5return5() // 5
val add:(Int,Int) => Int = (x,y) => x+y
add(7,3) // 10
TU Dresden, 07.05.2009 Scala Folie 14 von 21
Higher Order Functions
• Funktionen die andere Funktionen als Parameter nehmen oder zurück geben
def exists[T](list:List[T], f:T => Boolean ):Boolean = {for(item <- list)if(f(item)) return true
return false}}
val l = List(2,3,5,7,8,10)println(exists(l, n => n % 4 == 0)) // trueprintln(exists(l, n => n < 0)) // false
println(exists(pList, p => p.Age > 18)) // true
TU Dresden, 07.05.2009 Scala Folie 15 von 21
Closures
• Funktionen die auf Variablen zugreifen können die in ihrem Scope liegen
def findPersonbyName(name:String):Person = {personList.filter(p => p.Name == name)
}
var x = 3var x = 3val printX: () => Unit = () => println(x)printX() // 3
x = 23
printX() // 23
TU Dresden, 07.05.2009 Scala Folie 16 von 21
Tail Recursion
def factorial(n:BigInt):BigInt = {if(n == 1) 1 else n * factorial(n-1)
}
println(factorial(10)) // 3628800println(factorial(5000)) // StackOverflowError
def factorial2(akk:BigInt,n:BigInt):BigInt = {if(n == 1) akk else factorial2(akk*n,n-1)
}
println(factorial2(1,5000)) // 42285779……………
TU Dresden, 11.05.2009 Scala Folie 17 von 21
Currying
• ist die Umwandlung einer Funktion mit mehreren Argumenten in mehrere Funktionen mit je einem Argument
def factorial3(akk:BigInt)(n:BigInt):BigInt = {if(n == 1) akk else factorial2(akk*n n-1)if(n == 1) akk else factorial2(akk n,n 1)
}
println(factorial3(1)(7)) // 5400
• Partial Application
def fact = factorial3(1)_//println(fact(8)) // 40320
TU Dresden, 07.05.2009 Scala Folie 18 von 21
Pattern Matchingdef factorial4(akk:Int, i:Int):Int = {
i match {case 1 => akkcase n => factorial2(akk*n, n-1)
}}println(factorial4(1,9)) // 362880
def tup(exp:Any) = {def tup(exp:Any) = {exp match {case (a,b) => println("Matched:" + a + "," + b)case (a) => println("Matched:" + a )
}}println(tup(5)) // Matched:5
//println(tup(("Bob",25))) // Matched:Bob,25
TU Dresden, 07.05.2009 Scala Folie 19 von 21
Quellen
• Offizielle Seitewww.scala-lang.org
• Scala by Examplehttp://www.scala-lang.org/docu/files/ScalaByExample.pdf
• Scala Tutorialhttp://www.scala-lang.org/docu/files/ScalaTutorial.pdf
• ScalaTest Framework• ScalaTest Frameworkhttp://www.artima.com/scalatest/
• A Weblog by Martin Oderskyhttp://www.artima.com/weblogs/index.jsp?blogger=moderskyp // / g / j p gg y
• www.wikipedia.de
TU Dresden, 07.05.2009 Scala Folie 20 von 21
Fragen
Fragen?
TU Dresden, 07.05.2009 Scala Folie 21 von 21