<<  Penn iPhone - Voice over IP Презентация ЗАО МАТВЕЕВСКОЕ  >>
Scala: How to make best use of functions and objects
Scala: How to make best use of functions and objects
Scala in serious use
Scala in serious use
How to get started
How to get started
How to find out more
How to find out more
How to find out more
How to find out more
Картинки из презентации «Scala: How to make best use of functions and objects» к уроку экономики на тему «Компании»

Автор: odersky. Чтобы познакомиться с картинкой полного размера, нажмите на её эскиз. Чтобы можно было использовать все картинки для урока экономики, скачайте бесплатно презентацию «Scala: How to make best use of functions and objects.ppt» со всеми картинками в zip-архиве размером 810 КБ.

Scala: How to make best use of functions and objects

содержание презентации «Scala: How to make best use of functions and objects.ppt»
Сл Текст Сл Текст
1Scala: How to make best use of 33action1 ... case msgpatn => actionn }.
functions and objects. Phillip Haller A partial function of type
Lukas Rytz Martin Odersky EPFL ACM PartialFunction[MessageType, ActionType].
Symposium on Applied Computing Tutorial. 33.
2Where it comes from. Scala has 34A simple actor. case class Data(b:
established itself as one of the main Array[Byte]) case class GetSum(receiver:
alternative languages on the JVM. Actor) val checkSumCalculator = actor {
Prehistory: 1996 – 1997: Pizza 1998 – var sum = 0 loop { receive { case
2000: GJ, Java generics, javac ( “make Data(bytes) => sum += hash(bytes) case
Java better” ) Timeline: 2003 – 2006: The GetSum(receiver) => receiver ! sum } }
Scala “Experiment” 2006 – 2009: An }. 34.
industrial strength programming language ( 35Implementing receive. Using partial
“make a better Java” ). 2. functions, it is straightforward to
33. implement receive: Here, self designates
4Why Scala? 4. the currently executing actor, mailBox is
5Scala is a Unifier. Agile, with its queue of pending messages, and
lightweight syntax Object-Oriented Scala extractFirst extracts first queue element
Functional Safe and performant, with matching given predicate. def receive [A]
strong static tpying. 5. (f: PartialFunction[Message, A]): A = {
6What others say: 6. self.mailBox.extractFirst(f.isDefinedAt)
7“If I were to pick a language to use match { case Some(msg) => f(msg) case
today other than Java, it would be Scala.” None => self.wait(messageSent) } }. 35.
- James Gosling, creator of Java “Scala, 36Library or language? Experience:
it must be stated, is the current heir Initial versions of actors used one thread
apparent to the Java throne. No other per actor ? lack of speed and scalability
language on the JVM seems as capable of Later versions added a non-returning
being a "replacement for Java" `receive’ called react which makes actors
as Scala, and the momentum behind Scala is event-based. This gave great improvements
now unquestionable. While Scala is not a in scalability. New variants using
dynamic language, it has many of the delimited continuations are being explored
characteristics of popular dynamic (this ICFP). A possible objection to
languages, through its rich and flexible Scala's library-based approach is: Why
type system, its sparse and clean syntax, define actors in a library when they exist
and its marriage of functional and object already in purer, more optimized form in
paradigms.” - Charles Nutter, creator of Erlang? First reason: interoperability
JRuby “I can honestly say if someone had Another reason: libraries are much easier
shown me the Programming in Scala book by to extend and adapt than languages. 36.
Martin Odersky, Lex Spoon & Bill 37Scala cheat sheet (1): Definitions.
Venners back in 2003 I'd probably have Scala method definitions: def fun(x: Int):
never created Groovy.” - James Strachan, Int = { result } def fun = result Scala
creator of Groovy. 7. variable definitions: var x: int =
8Let’s see an example: 8. expression val x: String = expression.
9A class ... ... in Java: ... in Scala: Java method definition: int fun(int x) {
public class Person { public final String return result } (no parameterless methods)
name; public final int age; Person(String Java variable definitions: int x =
name, int age) { = name; expression final String x = expression.
this.age = age; } }. class Person(val 37.
name: String, val age: Int) {}. 9. 38Scala cheat sheet (2): Expressions.
10... and its usage. ... in Java: ... in Scala method calls: obj.meth(arg) or: obj
Scala: A function value. An infix method meth arg Scala choice expressions: if
call. A simple pattern match. import (cond) expr1 else expr2 expr match { case
java.util.ArrayList; ... Person[] people; pat1 => expr1 .... case patn =>
Person[] minors; Person[] adults; { exprn }. Java method call: obj.meth(arg)
ArrayList<Person> minorsList = new (no operator overloading) Java choice
ArrayList<Person>(); expressions, stats: cond ? expr1 : expr2
ArrayList<Person> adultsList = new // expression if (cond) return expr1; //
ArrayList<Person>(); for (int i = 0; statement else return expr2; switch (expr)
i < people.length; i++) (people[i].age { case pat1 : return expr1; ... case patn
< 18 ? minorsList : adultsList) : return exprn ; } // statement only. 38.
.add(people[i]); minors = 39Scala cheat sheet (3): Objects and
minorsList.toArray(people); adults = Classes. Scala Class and Object class
adultsList.toArray(people); }. val people: Sample(x: Int) { def instMeth(y: Int) = x
Array[Person] val (minors, adults) = + y } object Sample { def staticMeth(x:
people partition (_.age < 18). 10. Int, y: Int) = x * y }. Java Class with
11But there’s more to it. 11. static class Sample { final int x;
12Embedding Domain-Specific Languages. Sample(int x) { this.x = x } int
Scala’s flexible syntax makes it easy to instMeth(int y) { return x + y; } static
define high-level APIs & embedded DSLs int staticMeth(int x, int y) { return x *
Examples: - Scala actors (the core of y; } }. 39.
Twitter’s message queues) - specs, 40Scala cheat sheet (4): Traits. Scala
ScalaCheck - ScalaFX - ScalaQuery scalac’s Trait trait T { def abstractMeth(x:
plugin architecture makes it easy to String): String def concreteMeth(x:
typecheck DSLs and to enrich their String) = x+field var field = “!” } Scala
semantics. // asynchronous message send mixin composition: class C extends Super
actor ! message // message receive receive with T. Java Interface interface T {
{ case msgpat1 => action1 … case String abstractMeth(String x) (no concrete
msgpatn => actionn }. 12. methods) (no fields) } Java extension +
13The Essence of Scala. The work on implementation: class C extends Super
Scala was motivated by two hypotheses: implements T. 40.
Hypothesis 1: A general-purpose language 41Part 3: Programming in Scala. 41.
needs to be scalable; the same concepts 42Scala in serious use. You'll see now
should describe small as well as large how Scala's constructs play together in a
parts. Hypothesis 2: Scalability can be realistic application. Task: Write a
achieved by unifying and generalizing spreadsheet Start from scratch, don't use
functional and object-oriented programming any parts which are not in the standard
concepts. 13. libraries You'll see that this can be done
14Why unify FP and OOP? Both have in under 200 lines of code. Nevertheless
complementary strengths for composition: it demonstrates many aspects of
Functional programming: Makes it easy to scalability For comparison: Java demo: 850
build interesting things from simple LOC, MS Office 30Million LOC. 42.
parts, using higher-order functions, 43Step 1: The main function. package
algebraic types and pattern matching, scells import swing._ object Main extends
parametric polymorphism. Object-oriented SimpleGUIApplication { def top = new
programming: Makes it easy to adapt and MainFrame { title = "ScalaSheet"
extend complex systems, using subtyping contents += new SpreadSheet(100, 26) } }.
and inheritance, dynamic configurations, Advantage of objects over statics: objects
classes as partial abstractions. 14. can inherit. Hence, can hide low-level
15Scala. Scala is an object-oriented and fiddling necessary to set up a swing
functional language which is completely application. 43.
interoperable with Java. (the .NET version 44Step 2: The SpreadSheet class - view.
is currently under reconstruction.) It Property syntax; expands to method call
removes some of the more arcane constructs rowHeight_=(25). This calls in turn
of these environments and adds instead: jtable.setRowHeight(25). 44. class
(1) a uniform object model, (2) pattern SpreadSheet(val height: Int, val width:
matching and higher-order functions, (3) Int) extends ScrollPane { val cellModel =
novel ways to abstract and compose new Model(height, width) import
programs. 15. cellModel.{cells, valueChanged} val table
16Scala is interoperable. Scala programs = new Table(height, width) { rowHeight =
interoperate seamlessly with Java class 25 autoResizeMode =
libraries: Method calls Field accesses Table.AutoResizeMode.Off showGrid = true
Class inheritance Interface implementation gridColor = Color(150, 150, 150) def
all work as in Java. Scala programs userData(row: Int, column: Int): String =
compile to JVM bytecodes. Scala’s syntax { val v = this(row, column); if (v ==
resembles Java’s, but there are also some null) "" else v.toString }
differences. object instead of static override def render(isSelected: Boolean,
members. Array[String] instead of hasFocus: Boolean, row: Int, column: Int)
String[]. object Example1 { def main(args: = if (hasFocus) new
Array[String]) { val b = new TextField(userData(row, column)) else new
StringBuilder() for (i ? 0 until Label(cells(row)(column).toString) {
args.length) { if (i > 0) halign = Orientation.right } reactions +=
b.append(" ") { case event.TableChanged(table, firstRow,
b.append(args(i).toUpperCase) } lastRow, column) => for (row <-
Console.println(b.toString) } }. Scala’s firstRow to lastRow)
version of the extended for loop (use cells(row)(column).formula =
<- as an alias for ?). Arrays are FormulaParsers.parse(userData(row,
indexed args(i) instead of args[i]. 16. column)) case ValueChanged(cell) =>
17Scala is functional. The last program markUpdated(cell.row, cell.column) } for
can also be written in a completely (row <- cells; cell <- row)
different style: Treat arrays as instances listenTo(cell) } val rowHeader = new
of general sequence abstractions. Use ComponentList(0 until height map
higher-order functions instead of loops. (_.toString)) { fixedCellWidth = 30
Arrays are instances of sequences with map fixedCellHeight = table.rowHeight }
and mkString methods. map is a method of viewportView = table; rowHeaderView =
Array which applies the function on its rowHeader }.
right to each array element. object 45Step 3: The SpreadSheet class -
Example2 { def main(args: Array[String]) { controller. reactions property defines
println(args .map(_.toUpperCase) component behavior with closures. Import
.mkString(" ") } }. A closure can be used anywhere, not just at
which applies the toUpperCase method to top-level. Events are objects, can pattern
its String argument. mkString is a method match on them. 45. class SpreadSheet(val
of Array which forms a string of all height: Int, val width: Int) extends
elements with a given separator between ScrollPane { val cellModel = new
them. 17. Model(height, width) import
18Scala is concise. var capital = Map( cellModel.{cells, valueChanged} val table
"US" ? "Washington", = new Table(height, width) { rowHeight =
"France" ? "paris", 25 autoResizeMode =
"Japan" ? "tokyo" ) Table.AutoResizeMode.Off showGrid = true
capital += ( "Russia" ? gridColor = Color(150, 150, 150) def
"Moskow" ) for ( (country, city) userData(row: Int, column: Int): String =
? capital ) capital += ( country ? { val v = this(row, column) if (v == null)
city.capitalize ) assert ( "" else v.toString } override
capital("Japan") == def render(isSelected: Boolean, hasFocus:
"Tokyo" ). Scala’s syntax is Boolean, row: Int, column: Int) = if
lightweight and concise. Contributors: (hasFocus) new TextField(userData(row,
semicolon inference, type inference, column)) else new
lightweight classes, extensible API’s, Label(cells(row)(column).toString) {
closures as control abstractions. Average halign = Orientation.right } reactions +=
reduction in LOC wrt Java: ? 2 due to { case event.TableChanged(table, firstRow,
concise syntax and better abstraction lastRow, column) => for (row <-
capabilities ***** Guy Steele: Scala led firstRow to lastRow)
to a 4 times LOC reduction in the Fortress cells(row)(column).formula =
typechecker *****. 18. FormulaParsers.parse(userData(row,
19Scala is precise. All code on the column)) case ValueChanged(cell) =>
previous slide used library abstractions, markUpdated(cell.row, cell.column) } for
not special syntax. Advantage: Libraries (row <- cells; cell <- row)
are extensible and give fine- grained listenTo(cell) } val rowHeader = new
control. Elaborate static type system ComponentList((0 until height) map
catches many errors early. Specify map (_.toString)) { fixedCellWidth = 30
implementation: HashMap Specify map type: fixedCellHeight = table.rowHeight }
String to String. Specify kind of viewportView = table; owHeaderView =
collections: mutable. import rowHeader }.
scala.collection.mutable._ val capital = 46Spreadsheet formulas. We consider:
new HashMap[String, String] with -12.34 Number text Text label =expr
SynchronizedMap[String, String] { override Formulas, consisting of B12 Cell B12:C18
def default(key: String) = "?" } Range of cells add(A7,A4) Binary operation
capital += ( "US" ? sum(A12:A14,A16) Vararg operation (no
"Washington", "France" infix operations such as X+Y) Formula
? "Paris", "Japan" ? expressions can nest, as in: =sum(mul(A4,
"Tokyo" ) assert( 2.0), B7:B15)). 46.
capital("Russia") == 47Step 4: Representing formulas
"?" ). Mixin trait internally. B12 becomes Coord(12, 1). Case
SynchronizedMap to make capital map classes enable pattern matching. B0:B9
thread-safe. Provide a default value: becomes Range(Coord(0, 1), Coord(9, 1).
"?" 19. -12.34 becomes Number(-12.34d). ``Sales
20Big or small? Every language design forecast'' becomes Textual("Sales
faces the tension whether it should be big forcast"). add(A7, 42) becomes
or small: Big is good: expressive, easy to Application(Coord(7, 0), Number(42)). 47.
use. Small is good: elegant, easy to trait Formula {} case class Coord(row:
learn. Can a language be both big and Int, column: Int) extends Formula {
small? Scala’s approach: concentrate on override def toString = ('A' +
abstraction and composition capabilities column).toChar.toString + row } case class
instead of basic language constructs. Range(c1: Coord, c2: Coord) extends
Scala adds. Scala removes. + a pure object Formula { override def toString =
system. - static members. + operator c1.toString+":"+c2.toString }
overloading. - special treatment of case class Number(value: Double) extends
primitive types. + closures as control Formula { override def toString =
abstractions. - break, continue. + mixin value.toString } case class Textual(value:
composition with traits. - special String) extends Formula { override def
treatment of interfaces. + abstract type toString = value.toString } case class
members. - wildcards. + pattern matching. Application(function: String, arguments:
20. List[Formula]) extends Formula { override
21Scala is extensible. Guy Steele has def toString =
formulated a benchmark for measuring function+arguments.mkString("(",
language extensibility [Growing a quot;, ",")") } object
Language, OOPSLA 98]: Can you add a type Empty extends Textual("").
of complex numbers to the library and make 48A grammar for formulas. number =
it work as if it was a native number type? -?\d+(\.\d*) ident = [A-Za-z_]\w* cell =
Similar problems: Adding type BigInt, [A-Za-Z]\d+ range = cell : cell
Decimal, Intervals, Polynomials... application = ident ( expr (, expr)* )
scala> import Complex._ import expr = number | cell | range | application
Complex._ scala> val x = 1 + 1 * i x: formula = = expr textual = [^=].*. 48.
Complex = 1.0+1.0*i scala> val y = x * 49A grammar for formulas and their
i y: Complex = -1.0+1.0*i scala> val z parsers. number = -?\d+(\.\d*)
= y + 1 z: Complex = 0.0+1.0*i. 21. """-?\d+(\.\d*)?""
22Implementing complex numbers. Infix ".r ident = [A-Za-z_]\w*
operations are method calls: a + b is the """[a-zA-Z_]\w*""
same as a.+(b). Objects replace static quot;.r cell = [A-Za-Z]\d+
class members. + is an identifier; can be """
used as a method name. Class parameters [A-Za-z]\d\d*""".r range =
instead of fields+ explicit constructor. cell : cell cell~":"~cell
Implicit conversions for mixed arithmetic. application = ident ident~ ( expr (,
object Complex { val i = new Complex(0, 1) expr)* ) "("~repsep(expr,
implicit def double2complex(x: Double): ",")~")" expr = number
Complex = new Complex(x, 0) ... } class number | cell | range | | cell application
Complex(val re: Double, val im: Double) { | range | application formula = = expr
def + (that: Complex): Complex = new "="~expr textual = [^=].*
Complex( +, + """[^=].*""" def - (that: Complex): Complex = r. 49.
new Complex( -, - 50Step 5: Parsing formulas. This makes def * (that: Complex): Complex = use of an internal DSL, much like the
new Complex( * - * external Lex and Yacc. 50. def, * + * application: Parser[Application] = def / (that: Complex): Complex = ident~"("~repsep(expr,
{ val denom = * + ",")~")" ^^ { case
* new Complex(( * + f~"("~ps~")" => * / denom, ( * Application(f, ps) } def expr: - * / denom) } Parser[Formula] = application | range |
override def toString = re+(if (im < 0) cell | number def textual: Parser[Textual]
"-"+(-im) else =
"+"+im)+"*I" ... }. """[^=].*"""
22. r ^^ Textual def formula: Parser[Formula]
23Implicits are Poor Man’s Type Classes. = number | textual | "=" ~>
/** A “type class” */ class Ord[T] { def expr def parse(input: String): Formula =
< (x: T, y: T): Boolean } /** An parseAll(formula, input) match { case
“instance definition” */ implicit object Success(e, _) => e case f: NoSuccess
intOrd extends Ord[Int] { def < (x: =>
Int, y: Int) = x < y } /** Another Textual("["+f.msg+"]")
instance definition */ implicit def } }. object FormulaParsers extends
listOrd[T](implicit tOrd: Ord[T]) = new RegexParsers { def ident: Parser[String] =
Ord { def < (xs: List[T], ys: List[T]) """[a-zA-Z_]\w*""
= (xs, ys) match { case (_, Nil) => quot;.r def decimal: Parser[String] =
false case (Nil, _) => true case (x :: """-?\d+(\.\d*)?""
xs, y :: ts) => x < y || x == y ".r def cell: Parser[Coord] =
&& xs < ys } }. 23. """[A-Za-z]\d+""&
24The Bottom Line. When going from Java uot;.r ^^ { s => val column =
to Scala, expect at least a factor of 2 s.charAt(0) - 'A' val row =
reduction in LOC. But does it matter? s.substring(1).toInt Coord(row, column) }
Doesn’t Eclipse write these extra lines def range: Parser[Range] =
for me? This does matter. Eye-tracking cell~":"~cell ^^ { case
experiments* show that for program c1~":"~c2 => Range(c1, c2) }
comprehension, average time spent per word def number: Parser[Number] = decimal ^^ (s
of source code is constant. So, roughly, => Number(s.toDouble)).
half the code means half the time 51Step 6: Evaluating formulas. Evaluate
necessary to understand it. 24. *G. by pattern matching on the kind of
Dubochet. Computer Code as a Medium for formula. Scala's Self-type feature lets us
Human Communication: Are Programming assume the type of this in Evaluator is
Languages Improving? In 21st Annual Model. But how does Evaluator know about
Psychology of Programming Interest Group cells? 51. trait Evaluator { this: Model
Conference, pages 174-187, Limerick, => val operations = new
Ireland, 2009. collection.mutable.HashMap[String,
25Part 2: The Scala Design. 25. List[Double] => Double] def evaluate(e:
26The Scala design. Scala strives for Formula): Double = e match { case
the tightest possible integration of OOP Number(v) => v case Textual(_) => 0
and FP in a statically typed language. case Coord(row, column) =>
This continues to have unexpected cells(row)(column).value case
consequences. Scala unifies algebraic data Application(function, arguments) => val
types with class hierarchies, functions argvals = arguments flatMap evalList
with objects This gives a nice & operations(function)(argvals) } private
rather efficient formulation of Erlang def evalList(e: Formula): List[Double] = e
style actors. 26. match { case Range(_, _) =>
27ADTs are class hierarchies. Many references(e) map (_.value) case _ =>
functional languages have algebraic data List(evaluate(e)) } def references(e:
types and pattern matching. ? Concise and Formula): List[Cell] = e match { case
canonical manipulation of data structures. Coord(row, column) =>
Object-oriented programmers object: ADTs List(cells(row)(column)) case
are not extensible, ADTs violate the Range(Coord(r1, c1), Coord(r2, c2)) =>
purity of the OO data model, Pattern for (row <- (r1 to r2).toList; column
matching breaks encapsulation, and it <- c1 to c2) yield cells(row)(column)
violates representation independence! 27. case Application(function, arguments)
28Pattern matching in Scala. Here's a a => arguments flatMap references case
set of definitions describing binary => List() }.
trees: And here's an inorder traversal of 52Step 7: The spreadsheet Model class.
binary trees: This design keeps purity: Property definitions make interesting
all cases are classes or objects. things happen when variables are set. 52.
extensibility: you can define more cases class Model(val height: Int, val width:
elsewhere. encapsulation: only parameters int) extends Evaluator with Arithmetic {
of case classes are revealed. class Cell(row: Int, column: Int) extends
representation independence using Publisher { private var v: Double = 0 def
extractors [ECOOP 07]. The case modifier value: Double = v def value_=(w: Double) {
of an object or class means you can if (!(v == w || v.isNaN &&
pattern match on it. abstract class w.isNaN)) { v = w
Tree[T] case object Empty extends publish(ValueChanged(this)) } } private
Tree[Nothing] case class Binary[T](elem: var e: Formula = Empty def formula:
T, left: Tree[T], right: Tree[T]) extends Formula = e def formula_=(e: Formula) {
Tree[T]. def inOrder [T] ( t: Tree[T] ): for (c <- references(formula))
List[T] = t match { case Empty => deafTo(c) this.e = e for (c <-
List() case Binary(e, l, r) => references(formula)) listenTo(c) value =
inOrder(l) ::: List(e) ::: inOrder(r) }. evaluate(e) } reactions += { case
28. ValueChanged(_) => value =
29Extractors. ... are objects with evaluate(formula) } } case class
unapply methods. ... similar to active ValueChanged(cell: Cell) extends
patterns in F# unapply is called event.Event val cells =
implicitly for pattern matching. object Array.fromFunction(new Cell(_, _))(width,
Twice { def apply(x: Int) = x*2 def height) }.
unapply(z: Int): Option[Int] = if (z%2==0) 53Lessons learned. DSL's can help keep
Some(z/2) else None } val x = Twice(21) x software short and clear: Parser
match { case Twice(y) => combinators, swing components and
println(x+" is two times "+y) reactions. Internal DSLs have advantages
case _ => println("x is odd") over external ones. Mixin composition +
} }. 29. self types let you write fully re-entrant
30Functions are objects. Scala is a complex systems without any statics.
functional language, in the sense that Application complexity can be reduced by
every function is a value. If functions the right language constructs. To ensure
are values, and values are objects, it you always have the right constructs, you
follows that functions themselves are need a language that's extensible and
objects. The function type S => T is scalable. 53.
equivalent to scala.Function1[S, T] where 54But how long will it take me to
Function1 is defined as follows : So switch? 54.
functions are interpreted as objects with 55Alex Payne, Twitter: “Ops doesn’t know
apply methods. For example, the anonymous it’s not Java”. Learning Curves. Scala.
successor function (x: Int ) => x + 1 Alex McGuire, EDF, who replaced majority
is expanded to. new Function1[Int, Int] { of 300K lines Java with Scala: “Picking up
def apply(x: Int): Int = x + 1 }. trait Scala was really easy.” “Begin by writing
Function1[-S, +T] { def apply(x: S): T }. Scala in Java style.” “With Scala you can
30. mix and match with your old Java.” “You
31Why should I care? Since (=>) is a can manage risk really well.”.
class, it can be subclassed. So one can Productivity. 200%. 100%. Keeps familiar
specialize the concept of a function. An environment: : IDE’s: Eclipse, IDEA,
obvious use is for arrays, which are Netbeans, ... Tools: JavaRebel, FindBugs,
mutable functions over integer ranges. Maven, ... Libraries: nio, collections,
Another bit of syntactic sugaring lets one FJ, ... Frameworks; Spring, OSDI, J2EE,
write: a(i) = a(i) + 2 for a.update(i, ... ...all work out of the box. . 0%. 4-6
a.apply(i) + 2). class Array [T] ( length: weeks. 8-12 weeks. 55.
Int ) extends (Int => T) { def length: 56How to get started. 100s of resources
Int = ... def apply(i: Int): A = ... def on the web. Here are three great entry
update(i: Int, x: A): unit = ... def points: Simply Scala Scalazine @
elements: Iterator[A] = ... def exists(p: Scala for Java refugees. 56.
A => Boolean):Boolean = ... }. 31. 57How to find out more. Scala site:
32Partial functions. Another useful Six books this year.
abstraction are partial functions. These 57.
are functions that are defined only in 58Soon to come. New release Scala 2.8,
some part of their domain. What's more, with named and default parameters,
one can inquire with the isDefinedAt @specialized annotations for high
method whether a partial function is performance numerical computations,
defined for a given value. Scala treats improved IDE plugin support, and much
blocks of pattern matching cases as more. New version on .NET with Visual
instances of partial functions. This lets Studio integration. 58.
one write control structures that are not 59Long term focus: Concurrency &
easily expressible otherwise. trait Parallelism. Our goal: establish Scala as
PartialFunction[-A, +B] extends (A => the premier language for multicore
B) { def isDefinedAt(x: A): Boolean }. 32. programming. Actors gave us a head start.
33Example: Erlang-style actors. Two Actors as a library worked well because of
principal constructs (adopted from Scala’s flexible syntax and strong typing.
Erlang): Send (!) is asynchronous; The same mechanisms can also be brought to
messages are buffered in an actor's bear in the development of other
mailbox. receive picks the first message concurrency abstractions, such as:
in the mailbox which matches any of the parallel collections, software
patterns mspati. If no pattern matches, transactional memory, stream processing.
the actor suspends. // asynchronous 59.
message send actor ! message // message 60Thank You. 60.
receive receive { case msgpat1 =>
Scala: How to make best use of functions and objects.ppt
cсылка на страницу

Scala: How to make best use of functions and objects

другие презентации на тему «Scala: How to make best use of functions and objects»

«Ситимаг» - Конкурирующее окружение. Информация о клиенте. Магазин до приобретения франшизы СитиМаг. СитиМаг цены! Открытие магазина СитиМаг. Добро пожаловать, покупатели! 21 июня 2010. Открытие городского продовольственного магазина «СитиМаг» (г.Москва, ул.

«Керамика производство» - Области применения керамических пластин. Получение гранулята Гранулятор фирмы Niro A/S. Мировые тенденции развития технической керамики. Развитие керамического производства компании ХК ОАО «НЭВЗ-Союз». Для бронежилетов и бронетехники. Изоляторы для электронно-оптических преобразователей приборов ночного видения.

«Ауди Центр Варшавка» - Факторы успеха Что нужно для обеспечения желаемого уровня продаж. Планирование сезонности. На основе данных ГК АвтоСпецЦентр. Использование технических средств (CRM-программа) для персонализации маркетинговых коммуникаций. Аудит клиентской базы. Ауди Центр Варшавка Результаты работы в 2009 году. Входит в ГК АвтоСпецЦентр.

«Capstone» - Турбогенератор. Дым. Greenkraft. Выпущен демонстрационный образец класса 3/4* грузовой автомобиль с турбиной С30. Примечание: Результаты испытаний достигнуты без использования дополнительных систем очистки. Номинальная мощность. Velozzi. Природный газ, дизель биодизель, авиационное топливо. Модуль управления топливной системы.

«Тормозная жидкость» - OEM тормозные жидкости. 9. Дорожные испытания продолжение. – Гарантия жизни. 7. Сравнительный анализ. Фирменная транспортная коробка фасовка продукта 455 и 910 гр. 4. Разработка компании Тосол-Синтез. 9. Дорожные испытания. Тормозная жидкость ROSDOT 6 для систем ABS. 5. Внешний вид ROSDOT для систем ABS.

«Изделия из пластмассы» - Методы испытания. Маркировка изделий из пластмасс. На каждое изделие наносят товарный знак предприятия – изготовителя. Упаковка изделий из пластмасс. Хранение изделий из пластмасс. Требования к качеству изделий из пластических масс. Маркировка должна быть четкой, ясной и легко читаемой. Ассортимент и качество изделий из пластмасс.


40 презентаций о компаниях


125 тем
Картинки > Презентации по экономике > Компании > Scala: How to make best use of functions and objects