multiparadigm programming in scala

48 341 0
multiparadigm programming in scala

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Multiparadigm Programming Multiparadigm Programming in Scala in Scala Adapted from presentation by Adapted from presentation by H. C. Cunningham and J. C. Church H. C. Cunningham and J. C. Church University of Mississipi University of Mississipi What is Multiparadigm What is Multiparadigm Programming? Programming? Definition: Definition: A A multiparadigm programming language multiparadigm programming language provides provides “ “ a framework in which a framework in which programmers can work in a variety of programmers can work in a variety of styles, freely intermixing constructs styles, freely intermixing constructs from different paradigms. from different paradigms. ” ” [Tim Budd] [Tim Budd] Programming paradigms: Programming paradigms:  imperative versus declarative (e.g., imperative versus declarative (e.g., functional, logic) functional, logic)  other dimensions – object-oriented, component- other dimensions – object-oriented, component- oriented, concurrency-oriented, etc. oriented, concurrency-oriented, etc. ScalaMulti CS3180 (Prasad) 2 Why Learn Multiparadigm Why Learn Multiparadigm Programming? Programming? Tim Budd: Tim Budd: “ “ Research results from the psychology of Research results from the psychology of programming indicate that expertise in programming indicate that expertise in programming is far more strongly related to programming is far more strongly related to the number of different programming styles the number of different programming styles understood by an individual than it is the understood by an individual than it is the number of years number of years of experience in of experience in programming. programming. ” ” The The “ “ goal of multiparadigm computing is to goal of multiparadigm computing is to provide a number of different problem- provide a number of different problem- solving styles solving styles ” ” so that a programmer can so that a programmer can “ “ select a solution technique that best select a solution technique that best matches the characteristics of the problem matches the characteristics of the problem ” ” . . ScalaMulti CS3180 (Prasad) 3 Why Teach Multiparadigm Why Teach Multiparadigm Programming? Programming?  Contemporary imperative and object- Contemporary imperative and object- oriented languages increasingly have oriented languages increasingly have functional programming features, e.g., functional programming features, e.g., • higher order functions (closures) higher order functions (closures) • list comprehensions list comprehensions  New explicitly multiparadigm (object- New explicitly multiparadigm (object- oriented/functional) languages are oriented/functional) languages are appearing, e.g., appearing, e.g., • Scala on the Java platform (and .Net in Scala on the Java platform (and .Net in future) future) • F# on the .Net platform F# on the .Net platform ScalaMulti CS3180 (Prasad) 4 Scala Scala Programming language developed by Martin Programming language developed by Martin Odersky Odersky ’ ’ s team at EPFL in Switzerland s team at EPFL in Switzerland  Executes on the Java platform Executes on the Java platform  Integrates with Java Integrates with Java  Has growing usage (e.g., Twitter, Has growing usage (e.g., Twitter, Foursquare, and Linkedin) Foursquare, and Linkedin) Multiparadigm language Multiparadigm language  Object-oriented (with generics and mixins) Object-oriented (with generics and mixins)  Functional (similar to Haskell and SML) Functional (similar to Haskell and SML)  Extensible (method calls as operators, Extensible (method calls as operators, currying, closures, by-name parameters) currying, closures, by-name parameters) • Actor-based concurrency-oriented programming Actor-based concurrency-oriented programming • Language-oriented programming Language-oriented programming  Statically typed with Hindley-Milner type Statically typed with Hindley-Milner type inference inference ScalaMulti CS3180 (Prasad) 5 6 Why Scala? Why Scala? (Coming from Java/C++) (Coming from Java/C++)  Runs on the JVM Runs on the JVM  Can use any Java code in Scala Can use any Java code in Scala  Almost as fast as Java (within 10%) Almost as fast as Java (within 10%)  Much shorter code Much shorter code  Odersky reports 50% reduction in most code Odersky reports 50% reduction in most code over Java over Java  Local type inference Local type inference  Fewer errors Fewer errors  No Null Pointer problems No Null Pointer problems  More flexibility More flexibility  As many public classes per source file as As many public classes per source file as you want you want  Operator overloading Operator overloading Scala References Scala References  Website Website http://www.scala-lang.org http://www.scala-lang.org • Martin Odersky. Martin Odersky. Scala Tutorial for Java Programmers Scala Tutorial for Java Programmers . . • Martin Odersky. Martin Odersky. Scala By Example Scala By Example . .  Martin Odersky, Lex Spoon, and Bill Martin Odersky, Lex Spoon, and Bill Venners. Venners. Programming in Scala: A Programming in Scala: A Comprehensive Step-By-Step Guide Comprehensive Step-By-Step Guide , 2 , 2 nd nd Edition, Artima, Inc., 2010. Edition, Artima, Inc., 2010.  Books on Scala: Books on Scala: http://www.scala-lang.org/node/959 http://www.scala-lang.org/node/959 ScalaMulti CS3180 (Prasad) 7 8 Scala object system Scala object system  Class-based Class-based  Single inheritance Single inheritance  Can define singleton objects easily (no need for static Can define singleton objects easily (no need for static which is not really OO) which is not really OO)  Traits, compound types, and views allow for more Traits, compound types, and views allow for more flexibility flexibility 9 Basic Scala Basic Scala  Use Use var var to declare variables: to declare variables: var x = 3; var x = 3; x += 4; x += 4;  Use Use val val to declare values (final vars) to declare values (final vars) val y = 3; val y = 3; y += 4; // error y += 4; // error  Notice no types, but it is statically typed Notice no types, but it is statically typed var x = 3; var x = 3; x = x = “hello world”; // error “hello world”; // error  Type annotations: Type annotations: var x : Int = 3; var x : Int = 3; 10 Functional Scala Functional Scala  Defining lambdas – nameless functions Defining lambdas – nameless functions val f = x :Int => x + 42; val f = x :Int => x + 42; f : mapping :int f : mapping :int -> -> int int  Closures! Closures! A way to haul around state A way to haul around state var y = 3; var y = 3; val g = {x : Int => y += 1; x+y; } val g = {x : Int => y += 1; x+y; }  Maps (and a cool way to do some functions) Maps (and a cool way to do some functions) List(1,2,3).map(_+10).foreach(println) List(1,2,3).map(_+10).foreach(println)  Filtering (and ranges!) Filtering (and ranges!) 1 to 100 filter (_ % 7 == 3) foreach (println) 1 to 100 filter (_ % 7 == 3) foreach (println)  (Feels a bit like (Feels a bit like UNIX pipes UNIX pipes ?) ?) [...]... (Prasad) ScalaMulti 33 Partial Application scala> def addc(x: Int)(y: Int) = x + y addc: (Int)(Int)Int scala> val z = addc(1) _ z: (Int) => Int = scala> z(3) res2: Int = 4 CS3180 (Prasad) ScalaMulti 34 Closures scala> val inc = 10 inc: Int = 10 scala> def incre(x: Int) = x + inc incre: (Int)Int scala> def app(y: Int, g: (Int=>Int)) = g(y) app: (Int,(Int) => Int)Int scala> app(13,incre) res0: Int... allowing partial application Are often passed in a closure – with references to free variables they maninpulate Provide ability to build powerful libraries of higher-order functions CS3180 (Prasad) ScalaMulti 32 Curried Functions scala> def add(x: Int, y: Int) = x + y add: (Int,Int)Int scala> add(1,3) res0: Int = 4 scala> def addc(x: Int)(y: Int) = x + y addc: (Int)(Int)Int scala> addc(1)(3) res1: Int... them evaluated Type :help for more information scala> object HelloWorld { | def main(args: Array[String]) { | println("Hey world!") | } |} defined module HelloWorld scala> HelloWorld.main(null) Hey world! unnamed0: Unit = () scala> :q CS3180 (Prasad) ScalaMulti 12 Compiling & Executing Hello World > scalac HelloWorld .scala > scala HelloWorld Hey world! CS3180 (Prasad) ScalaMulti 13 Numbers are Objects...Defining Hello World object HelloWorld { def main(args: Array[String]){ println("Hey world!") } }  Singleton object named HelloWorld (also replaces static methods and variables)  Method main defined (procedure)  Parameter args of type Array[String]  Array is generic class with type parameter CS3180 (Prasad) ScalaMulti 11 Interpreting Hello World > scala This is a Scala shell Type in expressions... CS3180 (Prasad) ScalaMulti 19 Using Classes and Objects scala> :load Complex .scala Loading Complex .scala defined class Complex scala> val x = new Complex(1,-3) x: Complex = 1.0-3.0i scala> x.toString res0: java.lang.String = 1.0-3.0i CS3180 (Prasad) ScalaMulti 20 Case Classes abstract class Tree // Expression Trees case class Sum(l: Tree, r: Tree) extends Tree case class Var(n: String) extends Tree... case "x" => 5 case "y" => 7 } println("Expression: " + exp) println("Evaluation with x=5, y=7: " + eval(exp,env)) println("Derivative relative to x:\n " + derive(exp, "x")) println("Derivative relative to y:\n " + derive(exp, "y")) } } CS3180 (Prasad) ScalaMulti 23 Execute Expression Trees scala> :load Expressions .scala Loading Expressions .scala … scala> Expressions.main(null) Expression: Sum(Sum(Var(x),Var(x)),Sum(Const(7),Var(y)))... that) }  Like Java interfaces except can have concrete methods  Can be “mixed -in to class  Note that < is abstract; others defined with < and equals CS3180 (Prasad) ScalaMulti 26 Date Class with Mixin Trait Ord class Date(y: Int, m: Int, d: Int) extends Ord { def year = y def month = m def day = d override def toString(): String = year + "-" + month + "-" + day // … need definition of < and equals... (Prasad) ScalaMulti 14 Functions are Objects object Timer { def oncePerSecond(callback:() => Unit){ while (true) { callback(); Thread sleep 1000 } // 1-arg method sleep used as operator } def welcome() { println("Welcome to CS3180!") } def main(args: Array[String]) { oncePerSecond(welcome) } } CS3180 (Prasad) ScalaMulti 15 Timer Execution scala> :l Timer .scala Loading Timer .scala defined module Timer scala> ... class Const(v: int) extends Tree    Cf Algebraic data types as in functional languages Keyword new not needed to create instances (objects) Getters defined automatically for constructor parameters   Pattern matching can be used to decompose equals method defined on structure of instances CS3180 (Prasad) ScalaMulti 21 Pattern Matching object Expressions { type Environ = String => Int def eval(t:... (Prasad) ScalaMulti 24 Defs, Vals, and Vars Three types of identifier definitions: def defines functions with parameters; RHS expression evaluated each time called val defines unchanging values; RHS expression evaluated immediately to initialize var defines storage location whose values can be changed by assignment statements; RHS expression evaluated immediately to initialize CS3180 (Prasad) ScalaMulti . Mississipi What is Multiparadigm What is Multiparadigm Programming? Programming? Definition: Definition: A A multiparadigm programming language multiparadigm programming language provides. Multiparadigm Programming Multiparadigm Programming in Scala in Scala Adapted from presentation by Adapted from presentation by H. C. Cunningham and J. C. Church H. C. Cunningham and. results from the psychology of programming indicate that expertise in programming indicate that expertise in programming is far more strongly related to programming is far more strongly related

Ngày đăng: 24/10/2014, 13:47

Mục lục

  • Multiparadigm Programming in Scala

  • What is Multiparadigm Programming?

  • Why Learn Multiparadigm Programming?

  • Why Teach Multiparadigm Programming?

  • Scala

  • Why Scala? (Coming from Java/C++)

  • Scala References

  • Scala object system

  • Basic Scala

  • Functional Scala

  • Defining Hello World

  • Interpreting Hello World

  • Compiling & Executing Hello World

  • Numbers are Objects

  • Functions are Objects

  • Timer Execution

  • Anonymous Functions

  • Classes

  • Method Overriding

  • Using Classes and Objects

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan