A brief Scala introduction… Or – LoveGame in 4 lines of code… Move over Java, here comes Scala…
Some questions… <ul><li>Please ask questions if you are curious! – Interactive conversation! </li></ul><ul><li>43 slides a...
Quick love game run through <ul><li>Who knows what the love game is? </li></ul><ul><li>Going to demonstrate the language t...
The Love Game <ul><li>We will start off by going over the Love Game java pseudo code… </li></ul><ul><ul><li>( I actually h...
Java - LoveGame <ul><li>DISPLAY argument 0 + “ “ + argument 1 + “ “ + argument 2 + “ “ + argument 3 + “ “ + argument 4 </l...
Java – LoveGame 2 <ul><li>DECLARE tallyCounter </li></ul><ul><li>DECLARE totalAdder </li></ul><ul><li>//Calculates the per...
Scala - LoveGame <ul><li>Most of this improvement is due to being able to write in a functional manner vs the imperative s...
History <ul><li>Scala was created at the  École Polytechnique Fédérale de Lausanne  (EPFL) in 2001 by  Martin Odersky .  <...
Woah. (Scala Features) <ul><li>Scala is object-oriented  </li></ul><ul><ul><li>Everything is an object! </li></ul></ul><ul...
Woah. (Scala Features) <ul><li>Scala is functional  </li></ul><ul><ul><li>every function is a value   </li></ul></ul><ul><...
Woah. (Scala Features) <ul><li>Scala is statically typed </li></ul><ul><ul><li>Not dynamic – No speed trade off’s (Compare...
Recursive version <ul><li>For demonstration purposes, we will work with my original recursive (slightly longer) version </...
Line by line… The Map Function and Higher-Order Functions <ul><li>val initialList =  &quot;loves&quot; .toList.map(  F(x) ...
Method Signatures <ul><li>public   int  loveReduce(List<Integer> numbers) {…} </li></ul><ul><li>def   loveReduce (…)… </li...
Recall – Java Case statements <ul><li>// checks if a number between 1 and 10 is prime </li></ul><ul><li>int  number = 4; <...
Recall – Java Case statements <ul><li>If each case statement doesn’t return, need to also include break statements to prev...
Pattern Matching in Scala – Java case statements on steroids <ul><li>Generalised form of case statement </li></ul><ul><ul>...
Case statements in Scala <ul><li>But we can do better… </li></ul><ul><li>Drop the semicolons, of course </li></ul><ul><li>...
Pattern matching <ul><li>List constructor – the ‘cons’ notation – “::” </li></ul><ul><ul><li>head :: tail  // matches 1 or...
Recursion in Functional Scala <ul><li>Who can describe what a recursive function is? </li></ul><ul><ul><li>Recursion in co...
Our reduce function <ul><li>For g(x) we need to return a list one element smaller in order for our recursion to work (i.e....
Recursion in Functional Scala <ul><li>loveReduce(numbers.zip(numbers.tail) </li></ul><ul><li>.map{ case   (a,   b)   =>   ...
Putting it all together -> Recursion <ul><li>def   loveReduce ( numbers :List [ Int ]) :Int   =   </li></ul><ul><li>number...
Java - LoveGame <ul><li>DISPLAY argument 0 + “ “ + argument 1 + “ “ + argument 2 + “ “ + argument 3 + “ “ + argument 4 </l...
Scala - LoveGame <ul><li>Note the optional ‘.’ notation </li></ul><ul><li>Which do you think will be easier to maintain? <...
For the cynics out there… smaller Java implementation <ul><li>public   static   int   loveMatch ( String   name1 ,   Strin...
And for the side ball…. <ul><li>C#.NET LINQ </li></ul><ul><li>var   loves   =  “ loves ” . Select ( x   =>  “ roger   fede...
More Scala to come… <ul><li>Pimp my library! </li></ul><ul><ul><li>Implicit conversion functions </li></ul></ul><ul><ul><u...
More Scala to come… <ul><li>Class properties VS instance variables </li></ul><ul><ul><li>Static? </li></ul></ul><ul><li>Cu...
Combinator Parsing <ul><li>Define language parsers out of context free grammar definitions </li></ul><ul><li>8 * ( 4 + 2 )...
Combinator Parsing <ul><li>object   ArithmeticParsers   extends   StandardTokenParsers   {   </li></ul><ul><li>lexical . d...
Combinator Parsing <ul><li>More complex and practical example: </li></ul><ul><li>(buy 100 IBM shares at max USD 45, sell 5...
Combinator Parsing <ul><li>// ClientOrder.java </li></ul><ul><li>public   class   ClientOrder   { </li></ul><ul><li>public...
Properties / Class Parameters <ul><li>Scala’s concise syntax </li></ul><ul><li>this is Java </li></ul><ul><li>class   MyCl...
Implicit Conversions (and mixins with traits) <ul><li>class MyRichString (str: String ) {   </li></ul><ul><li>def countOcc...
Working with XML with language level support <ul><li>Consider the following XML document: </li></ul><ul><li><html> </li></...
Working with XML with language level support <ul><li>This document can be created by the following Scala program: </li></u...
Working with XML with language level support <ul><li>It is possible to mix Scala expressions and XML: </li></ul><ul><li>ob...
Actors and Concurrency <ul><li>class   Ping ( count :   int ,   pong :   Actor )   extends   Actor   { </li></ul><ul><li>d...
Companion objects and Static <ul><li>Singleton and Static considered harmful </li></ul><ul><ul><li>Static methods cannot b...
More and more and more…. <ul><li>Nested Functions </li></ul><ul><li>By-name parameters </li></ul><ul><ul><li>Lazy evaluati...
More Technologies are out there! <ul><li>Expand your mind! </li></ul><ul><li>Online Ajax HelpRequestList program in 9 line...
The Full Article <ul><li>Read the article at: </li></ul><ul><ul><li>http://stubbisms.wordpress.com/2008/02/22/my-foray-int...
Upcoming SlideShare
Loading in...5
×

Scala Language Intro - Inspired by the Love Game

2,437

Published on

Published in: Business, Technology
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,437
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Scala Language Intro - Inspired by the Love Game

  1. 1. A brief Scala introduction… Or – LoveGame in 4 lines of code… Move over Java, here comes Scala…
  2. 2. Some questions… <ul><li>Please ask questions if you are curious! – Interactive conversation! </li></ul><ul><li>43 slides and counting – less than two minutes per slide, so we’ll be lucky! Just how keen are you? </li></ul><ul><li>Who knows or has used a functional language before? </li></ul><ul><li>Who has heard of Scala? Erlang, Lisp, Scheme? </li></ul><ul><li>Who knows what a POM is? (not pom poms ;) </li></ul><ul><li>I had tried out Groovy (Grails ++) but… </li></ul><ul><li>I kept hearing something called Scala mentioned with a lot of respect, wanted to give it a go, just needed an excuse! </li></ul>
  3. 3. Quick love game run through <ul><li>Who knows what the love game is? </li></ul><ul><li>Going to demonstrate the language through writing an algorithm </li></ul><ul><li>Demonstrate on the board </li></ul>
  4. 4. The Love Game <ul><li>We will start off by going over the Love Game java pseudo code… </li></ul><ul><ul><li>( I actually had trouble fitting it all onto the slide…!!) </li></ul></ul>
  5. 5. Java - LoveGame <ul><li>DISPLAY argument 0 + “ “ + argument 1 + “ “ + argument 2 + “ “ + argument 3 + “ “ + argument 4 </li></ul><ul><li>FORMAT bothNames = argument 0 + argument 1 + argument 3 + argument 4 </li></ul><ul><li>CHANGE bothNames toLowerCase() </li></ul><ul><li>FORMAT compWord = argument 2 </li></ul><ul><li>CHANGE compWord toLowerCase() </li></ul><ul><li>//Creates two character arrays to enable comparison. </li></ul><ul><li>CHANGE FORMAT bothNames to character array bothNamesArray </li></ul><ul><li>CHANGE FORMAT compWord to character array compWordArray </li></ul><ul><li>//Creates an Integer array to store count results </li></ul><ul><li>FORMAT Integer Array tallyArray = new Integer Array [compWord.length] </li></ul><ul><li>FORMAT tallyArrayPointer = 0 </li></ul><ul><li>FORMAT matchCounter = 0 </li></ul><ul><li>//While loop counts the occurrences of each letter. </li></ul><ul><li>PROCESS WHILE tallyArrayPointer is less than compWord.length </li></ul><ul><li>PROCESS FOR i = 0 ; i is less than bothNames.length; increment i </li></ul><ul><li>FORMAT char nameLetter = element i in array bothNamesArray </li></ul><ul><li>FORMAT compLetter = element tallyArrayPointer in array compWordArray </li></ul><ul><li>IF nameLetter = compLetter </li></ul><ul><li>THEN increment matchCounter </li></ul><ul><li>ENDIF </li></ul><ul><li>tallyArray[tallyArrayPointer] = matchCounter </li></ul><ul><li>END FOR </li></ul><ul><li>RESET matchCounter </li></ul><ul><li>INCREMENT tallyArrayPointer </li></ul><ul><li>END WHILE </li></ul>
  6. 6. Java – LoveGame 2 <ul><li>DECLARE tallyCounter </li></ul><ul><li>DECLARE totalAdder </li></ul><ul><li>//Calculates the percentage compatibility by taking consecutive elements in the array and </li></ul><ul><li>//adding them together. </li></ul><ul><li>PROCESS WHILE the third element of tallyArray is not equal to -1 </li></ul><ul><li>RESET tallyCounter </li></ul><ul><li>PROCESS WHILE tallyCounter is less than length of tallyArray -1 & tallyArray[tallyCounter+1] is not equal to -1 </li></ul><ul><li>totalAdder = tallyArray[tallyCounter] + tallyArray[tallyCounter + 1] </li></ul><ul><li>tallyArray[tallyCounter] = totalAdder </li></ul><ul><li>INCREMENT tallyCounter </li></ul><ul><li>END WHILE </li></ul><ul><li>tallyArray[tallyCounter] = -1 </li></ul><ul><li>END WHILE </li></ul><ul><li>DECLARE finalPercentage = (1st element of tallyArray + 2nd element of tallyArray) * 2 </li></ul><ul><li>DISPLAY Calculated compatibility = finalPercentage % </li></ul>
  7. 7. Scala - LoveGame <ul><li>Most of this improvement is due to being able to write in a functional manner vs the imperative style of looping and state manipulation </li></ul><ul><li>We will now elaborate… </li></ul><ul><li>The Love Game in 4 lines of code… </li></ul>var loves = &quot;loves&quot; . toList map ( x => &quot;roger federer maria sharapova&quot; . toList count ( x == _ )) while (loves . length > 1) loves = loves zip ( loves tail ) map { x => x . _1 + x . _2 } println ( &quot;3 line compatibility = &quot; + loves . head * 2 + &quot; %&quot; )
  8. 8. History <ul><li>Scala was created at the École Polytechnique Fédérale de Lausanne (EPFL) in 2001 by Martin Odersky . </li></ul><ul><li>It was released publicly on the Java platform in January 2004, and on the .NET platform in June the same year. A second version of the language was released in March 2006. </li></ul><ul><li>General purpose </li></ul><ul><li>Express common programming patterns in a concise , elegant , and type-safe way </li></ul><ul><li>Stands for “scalable language.” </li></ul><ul><ul><li>Designed to grow with the demands of its users. </li></ul></ul><ul><ul><li>Wide range of programming tasks, from small scripts to building large systems. </li></ul></ul><ul><li>Smoothly integrates features of object-oriented and functional languages. </li></ul><ul><li>Interoperable with Java . Both ways. </li></ul><ul><li>Aims to make the most common case, easy. </li></ul><ul><li>It is both a scripting language and a compiled one. </li></ul><ul><li>Imutability and lack of side effects are key to distributed paralleism which are features of functional languages - a modern issue facing IT today with multi core process. </li></ul><ul><li>So - compatibility, brevity, high-level abstractions </li></ul>
  9. 9. Woah. (Scala Features) <ul><li>Scala is object-oriented </li></ul><ul><ul><li>Everything is an object! </li></ul></ul><ul><ul><ul><li>every value, even primitives, are an object </li></ul></ul></ul><ul><ul><ul><li>Every function is an object </li></ul></ul></ul><ul><ul><ul><li>Most operators are actually methods! (operator overloading) </li></ul></ul></ul><ul><ul><ul><ul><li>2 * (4 + 6) is actually compiled to (4.+(6)).*(2) </li></ul></ul></ul></ul><ul><ul><li>Types and behaviour of objects are described by classes and traits </li></ul></ul><ul><ul><li>Multiple inheritance solution with mixins of traits </li></ul></ul><ul><ul><li>Strong type system – type inference, generics </li></ul></ul><ul><ul><li>singleton objects, </li></ul></ul><ul><ul><li>Traits </li></ul></ul><ul><ul><li>Uniform access principle - “…client code should not be affected by a decision to implement some attribute as a field or as a method.” </li></ul></ul>
  10. 10. Woah. (Scala Features) <ul><li>Scala is functional </li></ul><ul><ul><li>every function is a value </li></ul></ul><ul><ul><li>Higher-order functions </li></ul></ul><ul><ul><li>Anonymous functions </li></ul></ul><ul><ul><li>Function currying / partial functions </li></ul></ul><ul><ul><ul><li>(multiple parameter lists) </li></ul></ul></ul><ul><ul><li>Lazy evaluation </li></ul></ul><ul><ul><ul><ul><li>Infinite ranges </li></ul></ul></ul></ul><ul><ul><li>built-in support for pattern matching </li></ul></ul>
  11. 11. Woah. (Scala Features) <ul><li>Scala is statically typed </li></ul><ul><ul><li>Not dynamic – No speed trade off’s (Compared to Groovy and Ruby), but less flexible at runtime (can be argued either way) </li></ul></ul><ul><ul><li>But - Local type inference mechanism – don’t need to specify types if they can be inferred </li></ul></ul><ul><ul><li>Generics (parameterised types) </li></ul></ul><ul><li>Scala is extensible (scalable) </li></ul><ul><ul><li>Implicit type conversions </li></ul></ul><ul><ul><li>Allows language extensions - empowers you to create new language constructs </li></ul></ul><ul><ul><li>The much beloved “Pimp my Library pattern” </li></ul></ul><ul><ul><li>Unique combination of language mechanisms makes it easy to smoothly add new language constructs in the form of libraries </li></ul></ul><ul><li>Interoperates with Java and .NET (.NET support is ‘rough’ atm) </li></ul><ul><li>Optional semi colons, often option parenthesis and ‘dots’ </li></ul><ul><li>Built in language support for XML processing through natural extention of pattern matching </li></ul><ul><li>Great community </li></ul><ul><ul><li>Active mailing list – Martin himself replied to my query about Regex Parsers </li></ul></ul>
  12. 12. Recursive version <ul><li>For demonstration purposes, we will work with my original recursive (slightly longer) version </li></ul><ul><li>val initialList = &quot;loves&quot; . toList . map ( x => &quot;roger federer maria sharapova&quot; . toList . count ( x == _ )) </li></ul><ul><li>def loveReduce ( numbers : List [ Int ]): Int = numbers match { </li></ul><ul><li>case head :: Nil => head * 2 </li></ul><ul><li>case _ => loveReduce ( numbers . zip ( numbers . tail ). map { case ( a , b ) => a + b }) </li></ul><ul><li>} </li></ul><ul><li>println ( &quot;Compatibility = &quot; + loveReduce ( initialList ) + &quot; %&quot; ) </li></ul>
  13. 13. Line by line… The Map Function and Higher-Order Functions <ul><li>val initialList = &quot;loves&quot; .toList.map( F(x) ) </li></ul><ul><ul><ul><li>[ 1, 2, 3, 4] </li></ul></ul></ul><ul><ul><ul><ul><li>F(x) ------  </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>[ f(1), f(2), f(3), f(4) ] </li></ul></ul></ul></ul></ul><ul><ul><ul><li>If F(x) = x^2 we get : </li></ul></ul></ul><ul><ul><ul><ul><ul><li>[ f(1), f(4), f(9), f(16) ] </li></ul></ul></ul></ul></ul><ul><li>F(x) = &quot;roger federer maria sharapova&quot; .toList.count( H(y,x) ) </li></ul><ul><li>H(y,x) = y == x </li></ul><ul><li>val initialList = &quot;loves&quot; .toList.map( x => &quot;roger federer maria sharapova&quot; .toList.count( y => y == x )) </li></ul>
  14. 14. Method Signatures <ul><li>public int loveReduce(List<Integer> numbers) {…} </li></ul><ul><li>def loveReduce (…)… </li></ul><ul><li>def loveReduce ( numbers : List [ Int ]): Int … </li></ul><ul><ul><li>(Need to specify return type only for recursive functions, otherwise the compiler invokes the type inference mechanism) </li></ul></ul><ul><li>def loveReduce ( numbers : List [ Int ]): Int = numbers match {…} </li></ul><ul><ul><li>Don’t need surrounding braces as it’s a single statement </li></ul></ul>
  15. 15. Recall – Java Case statements <ul><li>// checks if a number between 1 and 10 is prime </li></ul><ul><li>int number = 4; </li></ul><ul><li>switch ( number ) { </li></ul><ul><li>case 1 : return true ; </li></ul><ul><li>case 2 : return true ; </li></ul><ul><li>case 3 : return true ; </li></ul><ul><li>case 5 : return true ; </li></ul><ul><li>case 7 : return true ; </li></ul><ul><li>default : return false ; </li></ul><ul><li>} </li></ul>
  16. 16. Recall – Java Case statements <ul><li>If each case statement doesn’t return, need to also include break statements to prevent unwanted fall through </li></ul><ul><li>switch ( number ) { </li></ul><ul><li>case 1 : object . operation1 ( number ); </li></ul><ul><li>break ; </li></ul><ul><li>case 2 : object . operation2 ( number ); </li></ul><ul><li>break ; </li></ul><ul><li>case 3 : object . operation3 ( number ); </li></ul><ul><li>break ; </li></ul><ul><li>case 5 : object . operation4 ( number ); </li></ul><ul><li>break ; </li></ul><ul><li>case 7 : object . operation5 ( number ); </li></ul><ul><li>break ; </li></ul><ul><li>default : object.defaultOp ( number ); </li></ul><ul><li>} </li></ul>
  17. 17. Pattern Matching in Scala – Java case statements on steroids <ul><li>Generalised form of case statement </li></ul><ul><ul><li>But more powerfull </li></ul></ul><ul><li>No ‘fall through’ (common case) </li></ul><ul><li>// checks if a number between 1 and 10 is prime </li></ul><ul><li>number match { </li></ul><ul><li>case 1 => return true; </li></ul><ul><li>case 2 => return true; </li></ul><ul><li>case 3 => return true; </li></ul><ul><li>case 5 => return true; </li></ul><ul><li>case 7 => return true; </li></ul><ul><li>case _ => return false; //similar to Java’s default case </li></ul><ul><li>} </li></ul>
  18. 18. Case statements in Scala <ul><li>But we can do better… </li></ul><ul><li>Drop the semicolons, of course </li></ul><ul><li>Drop the return statements </li></ul><ul><ul><li>Again, scala’s type inference kicks in – return value of function is simply last resolved statement </li></ul></ul><ul><li>// checks if a number between 1 and 10 is prime </li></ul><ul><li>number match { </li></ul><ul><li>case 1 => true </li></ul><ul><li>case 2 => true </li></ul><ul><li>case 3 => true </li></ul><ul><li>case 5 => true </li></ul><ul><li>case 7 => true </li></ul><ul><li>case _ => false </li></ul><ul><li>} </li></ul><ul><li>Clean eh? </li></ul>
  19. 19. Pattern matching <ul><li>List constructor – the ‘cons’ notation – “::” </li></ul><ul><ul><li>head :: tail // matches 1 or more (can also use foo :: bar ) </li></ul></ul><ul><ul><li>foo :: 2 // 2 element list where 2nd element is integer 2 </li></ul></ul><ul><ul><li>head :: Nil // Nil (is an object – extends List) represents an empty list – matches 1 element list </li></ul></ul><ul><ul><li>x :: xs // matches 1 or more </li></ul></ul><ul><li>Nil and :: are actually case Classes! </li></ul><ul><ul><li>remember, there is nearly no restriction on characters used for class and method names etc </li></ul></ul><ul><ul><li>Any method which takes a single parameter can be used as an infix operator – but :: (cons) when used in pattern matching is a special case </li></ul></ul><ul><ul><ul><li>That is, the infix operator “::” here, is treated as a constructor pattern ::(foo, bar) </li></ul></ul></ul><ul><ul><li>From scala-lang.org: Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching . </li></ul></ul><ul><ul><li>Checks the entire tree of the objects match </li></ul></ul><ul><ul><li>Can do things like: case Foo ( x , Bar ( y )) if x == y => true </li></ul></ul><ul><li>numbers match { </li></ul><ul><li>case head :: Nil => head * 2 </li></ul><ul><li>case _ => {…} </li></ul><ul><li>} </li></ul>
  20. 20. Recursion in Functional Scala <ul><li>Who can describe what a recursive function is? </li></ul><ul><ul><li>Recursion in computer programming defines a function in terms of itself. </li></ul></ul><ul><ul><li>Recursion: *see Recursion . </li></ul></ul><ul><li>def loveReduce ( ... )...{ </li></ul><ul><li>... </li></ul><ul><li>... loveReduce ( g(x) ) </li></ul><ul><li>} </li></ul>
  21. 21. Our reduce function <ul><li>For g(x) we need to return a list one element smaller in order for our recursion to work (i.e. reduce ) </li></ul><ul><ul><li>Step 1 </li></ul></ul><ul><li>numbers.zip(numbers.tail) </li></ul><ul><ul><li>Step 2 </li></ul></ul><ul><li>.map{ x => x._1 + x._2 } </li></ul><ul><li>Nicer syntax – using a match expresion in place of a function literal </li></ul><ul><li>.map{ case (a,b) => a + b } </li></ul><ul><ul><li>“ A match expression can be used anywhere a function literal can be used. Essentially, a match expression is a function literal, only more general.” </li></ul></ul>
  22. 22. Recursion in Functional Scala <ul><li>loveReduce(numbers.zip(numbers.tail) </li></ul><ul><li>.map{ case (a, b) => a+b}) </li></ul><ul><li>Each call, calls loveReduce, with a list one element smaller (due to the zip call) </li></ul>
  23. 23. Putting it all together -> Recursion <ul><li>def loveReduce ( numbers :List [ Int ]) :Int = </li></ul><ul><li>numbers match { </li></ul><ul><li>case head :: Nil => head * 2 </li></ul><ul><li>case _ => loveReduce ( numbers . zip ( numbers . tail ) </li></ul><ul><li>. map { case ( a , b ) => a + b }) </li></ul><ul><li>} </li></ul><ul><li>NB: Don’t need surrounding curly braces because it’s a single statement </li></ul>
  24. 24. Java - LoveGame <ul><li>DISPLAY argument 0 + “ “ + argument 1 + “ “ + argument 2 + “ “ + argument 3 + “ “ + argument 4 </li></ul><ul><li>FORMAT bothNames = argument 0 + argument 1 + argument 3 + argument 4 </li></ul><ul><li>CHANGE bothNames toLowerCase() </li></ul><ul><li>FORMAT compWord = argument 2 </li></ul><ul><li>CHANGE compWord toLowerCase() </li></ul><ul><li>//Creates two character arrays to enable comparison. </li></ul><ul><li>CHANGE FORMAT bothNames to character array bothNamesArray </li></ul><ul><li>CHANGE FORMAT compWord to character array compWordArray </li></ul><ul><li>//Creates an Integer array to store count results </li></ul><ul><li>FORMAT Integer Array tallyArray = new Integer Array [compWord.length] </li></ul><ul><li>FORMAT tallyArrayPointer = 0 </li></ul><ul><li>FORMAT matchCounter = 0 </li></ul><ul><li>//While loop counts the occurrences of each letter. </li></ul><ul><li>PROCESS WHILE tallyArrayPointer is less than compWord.length </li></ul><ul><li>PROCESS FOR i = 0 ; i is less than bothNames.length; increment i </li></ul><ul><li>FORMAT char nameLetter = element i in array bothNamesArray </li></ul><ul><li>FORMAT compLetter = element tallyArrayPointer in array compWordArray </li></ul><ul><li>IF nameLetter = compLetter </li></ul><ul><li>THEN increment matchCounter </li></ul><ul><li>ENDIF </li></ul><ul><li>tallyArray[tallyArrayPointer] = matchCounter </li></ul><ul><li>END FOR </li></ul><ul><li>RESET matchCounter </li></ul><ul><li>INCREMENT tallyArrayPointer </li></ul><ul><li>END WHILE </li></ul><ul><li>DECLARE tallyCounter </li></ul><ul><li>DECLARE totalAdder </li></ul><ul><li>//Calculates the percentage compatibility by taking consecutive elements in the array and </li></ul><ul><li>//adding them together. </li></ul><ul><li>PROCESS WHILE the third element of tallyArray is not equal to -1 </li></ul><ul><li>RESET tallyCounter </li></ul><ul><li>PROCESS WHILE tallyCounter is less than length of tallyArray -1 & tallyArray[tallyCounter+1] is not equal to -1 </li></ul><ul><li>totalAdder = tallyArray[tallyCounter] + tallyArray[tallyCounter + 1] </li></ul><ul><li>tallyArray[tallyCounter] = totalAdder </li></ul><ul><li>INCREMENT tallyCounter </li></ul><ul><li>END WHILE </li></ul><ul><li>tallyArray[tallyCounter] = -1 </li></ul><ul><li>END WHILE </li></ul><ul><li>DECLARE finalPercentage = (1st element of tallyArray + 2nd element of tallyArray) * 2 </li></ul><ul><li>DISPLAY Calculated compatibility = finalPercentage % </li></ul>
  25. 25. Scala - LoveGame <ul><li>Note the optional ‘.’ notation </li></ul><ul><li>Which do you think will be easier to maintain? </li></ul><ul><li>Any questions? </li></ul><ul><li>The Love Game in 4 lines of code… </li></ul><ul><li>var loves = &quot;loves&quot; . toList map ( x => &quot;roger federer maria sharapova&quot; . toList count ( x == _ )) </li></ul><ul><li>while ( loves . length > 1 ) </li></ul><ul><li>loves = loves zip ( loves tail ) map { x => x . _1 + x . _2 } </li></ul><ul><li>println ( &quot;3 line compatibility = &quot; + loves . head * 2 + &quot; %&quot; ) </li></ul>
  26. 26. For the cynics out there… smaller Java implementation <ul><li>public static int loveMatch ( String name1 , String name2 , String compWord ) { </li></ul><ul><li>int [] tally = new int [ compWord . length ()]; </li></ul><ul><li>for ( char c : ( name1 + name2 ). toCharArray ()) </li></ul><ul><li>for ( int t = 0 ; t < tally . length ; t ++) </li></ul><ul><li>if ( c == compWord . charAt ( t )) tally [ t ]++; </li></ul><ul><li>for ( int i = tally . length - 1 ; i >= 0 ; i --) </li></ul><ul><li>for ( int j = 0 ; j < i ; j ++) </li></ul><ul><li>tally [ j ] += tally [ j + 1 ]; </li></ul><ul><li>return tally [ 0 ] * 2 ; </li></ul><ul><li>} </li></ul>
  27. 27. And for the side ball…. <ul><li>C#.NET LINQ </li></ul><ul><li>var loves = “ loves ” . Select ( x => “ roger federer maria sharapova ” . Count ( c => x == c )). ToList (); </li></ul><ul><li>while ( loves . Count > 1 ) </li></ul><ul><li>loves = Enumerable . Range ( 0 , loves . Count - 1 ). Select ( i => loves [ i ] + loves [ i + 1 ]). ToList (); </li></ul><ul><li>Console . WriteLine ( loves . Single () * 2 ); </li></ul>
  28. 28. More Scala to come… <ul><li>Pimp my library! </li></ul><ul><ul><li>Implicit conversion functions </li></ul></ul><ul><ul><ul><li>Examples: </li></ul></ul></ul><ul><ul><ul><ul><li>MyRichString </li></ul></ul></ul></ul><ul><ul><li>E.g. JScience interface </li></ul></ul><ul><li>Measure length = Measure .valueOf(50, SI .CENTI( SI .METER)).plus( Measure .valueOf(25.0, SI .METER)); </li></ul><ul><li>Measure lengthInCentimeters = length .to( SI .CENTI( SI .METER)); </li></ul><ul><li>System.out .println ( &quot;length in centimeters is &quot; + lengthInCentimeters.getEstimatedValue()); </li></ul><ul><ul><li>VS </li></ul></ul><ul><ul><li>var len =  50 .centimeters +  25 .meters   </li></ul></ul><ul><ul><li>println(&quot; length in centimeters is  &quot; + len)   </li></ul></ul>
  29. 29. More Scala to come… <ul><li>Class properties VS instance variables </li></ul><ul><ul><li>Static? </li></ul></ul><ul><li>Currying </li></ul><ul><ul><li>the technique of transforming a function that takes multiple arguments into a function that takes a single argument (the other arguments having been specified by the curry). </li></ul></ul><ul><li>Advanced Pattern Matching and Case Classes </li></ul><ul><li>Actors Library </li></ul><ul><ul><li>concurrent processes that communicate by exchanging messages. </li></ul></ul>
  30. 30. Combinator Parsing <ul><li>Define language parsers out of context free grammar definitions </li></ul><ul><li>8 * ( 4 + 2 ) </li></ul><ul><li>expr ::= term { '+' term | ‘-’ term}. </li></ul><ul><li>term ::= factor { '*' factor | '/' factor}. </li></ul><ul><li>factor ::= numericLit | '(' expr ')'. </li></ul>
  31. 31. Combinator Parsing <ul><li>object ArithmeticParsers extends StandardTokenParsers { </li></ul><ul><li>lexical . delimiters ++= List ( &quot;(&quot; , &quot;)&quot; , &quot;+&quot; , &quot;-&quot; , &quot;*&quot; , &quot;/&quot; ) </li></ul><ul><li>def expr : Parser [ Any ] = term ~ rep ( &quot;+&quot; ~ term | &quot;-&quot; ~ term ) </li></ul><ul><li>def term = factor ~ rep ( &quot;*&quot; ~ factor | &quot;/&quot; ~ factor ) </li></ul><ul><li>def factor : Parser [ Any ] = &quot;(&quot; ~ expr ~ &quot;)&quot; | numericLit </li></ul><ul><li>} </li></ul><ul><li>val tokens = new lexical . Scanner ( args ( 0 )) </li></ul><ul><li>println ( args ( 0 )) </li></ul><ul><li>println ( phrase ( expr )( tokens )) </li></ul><ul><li>This of course also parses ( 36 / 8 * ( 4 + 2 ) ) / ( ( 5 – 3 ) * 6 ) </li></ul>
  32. 32. Combinator Parsing <ul><li>More complex and practical example: </li></ul><ul><li>(buy 100 IBM shares at max USD 45, sell 50 CISCO shares at min USD 25, buy 100 Google shares at max USD 800) for trading_account &quot;SSS1234&quot; </li></ul><ul><li>http://debasishg.blogspot.com/2008/04/external-dsls-made-easy-with-scala.html </li></ul>
  33. 33. Combinator Parsing <ul><li>// ClientOrder.java </li></ul><ul><li>public class ClientOrder { </li></ul><ul><li>public enum BuySell { </li></ul><ul><li>BUY , </li></ul><ul><li>SELL </li></ul><ul><li>} </li></ul><ul><li>private String accountNo ; </li></ul><ul><li>private List < LineItem > lineItems = new ArrayList < LineItem >(); </li></ul><ul><li>// LineItem.java </li></ul><ul><li>public class LineItem { </li></ul><ul><li>private final String security ; </li></ul><ul><li>private final int quantity ; </li></ul><ul><li>private final ClientOrder . BuySell bs ; </li></ul><ul><li>private final int price ; </li></ul><ul><li>public LineItem ( String security , int quantity , ClientOrder . BuySell bs , int price ) { </li></ul><ul><li>this . security = security ; </li></ul><ul><li>this . quantity = quantity ; </li></ul><ul><li>this . bs = bs ; </li></ul><ul><li>this . price = price ; </li></ul>
  34. 34. Properties / Class Parameters <ul><li>Scala’s concise syntax </li></ul><ul><li>this is Java </li></ul><ul><li>class MyClass { </li></ul><ul><li>private int index ; </li></ul><ul><li>private String name ; </li></ul><ul><li>public MyClass ( int index , String name ) { </li></ul><ul><li>this . index = index ; </li></ul><ul><li>this . name = name ; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>In Scala, you would likely write this instead: </li></ul><ul><li>class MyClass ( index : Int , name : String ) </li></ul>
  35. 35. Implicit Conversions (and mixins with traits) <ul><li>class MyRichString (str: String ) { </li></ul><ul><li>def countOccurances (haystack: String) = </li></ul><ul><li>str.toList.map( x => haystack.toList.count(x == _ )) </li></ul><ul><li>} </li></ul><ul><li>trait MyConversions { </li></ul><ul><li>implicit def string2MyRichString (str: String) = new MyRichString(str) </li></ul><ul><li>} </li></ul><ul><li>object MyConversionsTest extends Application with MyConversions { </li></ul><ul><li>val m = &quot;cow&quot; </li></ul><ul><li>println(m.countOccurances(&quot;o&quot;)) </li></ul><ul><li>} </li></ul>
  36. 36. Working with XML with language level support <ul><li>Consider the following XML document: </li></ul><ul><li><html> </li></ul><ul><li><head> </li></ul><ul><li><title> Hello XHTML world </title> </li></ul><ul><li></head> </li></ul><ul><li><body> </li></ul><ul><li><h1> Hello world </h1> </li></ul><ul><li><p><a href = &quot;http://scala-lang.org/&quot; > Scala </a> talks XHTML </p> </li></ul><ul><li></body> </li></ul><ul><li></html> </li></ul>
  37. 37. Working with XML with language level support <ul><li>This document can be created by the following Scala program: </li></ul><ul><li>val page = </li></ul><ul><li><html> </li></ul><ul><li><head> </li></ul><ul><li><title> Hello XHTML world </title> </li></ul><ul><li></head> </li></ul><ul><li><body> </li></ul><ul><li><h1> Hello world </h1> </li></ul><ul><li><p><a href = &quot;scala-lang.org&quot; > Scala </a> talks XHTML </p> </li></ul><ul><li></body> </li></ul><ul><li></html> ; </li></ul><ul><li>println(page.toString()) </li></ul>
  38. 38. Working with XML with language level support <ul><li>It is possible to mix Scala expressions and XML: </li></ul><ul><li>object XMLTest2 extends Application { </li></ul><ul><li>import scala . xml . _ </li></ul><ul><li>val df = java . text . DateFormat . getDateInstance () </li></ul><ul><li>val dateString = df . format ( new java . util . Date ()) </li></ul><ul><li>def theDate ( name : String ) = </li></ul><ul><li>< dateMsg addressedTo ={ name }> </li></ul><ul><li>Hello , { name }! Today is { dateString } </li></ul><ul><li></ dateMsg >; </li></ul><ul><li>println ( theDate ( &quot;John Doe&quot; ). toString ()) </li></ul><ul><li>} </li></ul>
  39. 39. Actors and Concurrency <ul><li>class Ping ( count : int , pong : Actor ) extends Actor { </li></ul><ul><li>def act () { </li></ul><ul><li>var pingsLeft = count - 1 </li></ul><ul><li>pong ! Ping </li></ul><ul><li>while ( true ) { </li></ul><ul><li>receive { </li></ul><ul><li>case Pong => </li></ul><ul><li>if ( pingsLeft % 1000 == 0 ) </li></ul><ul><li>Console . println ( &quot;Ping: pong&quot; ) </li></ul><ul><li>if ( pingsLeft > 0 ) { </li></ul><ul><li>pong ! Ping </li></ul><ul><li>pingsLeft -= 1 </li></ul><ul><li>} else { </li></ul><ul><li>Console . println ( &quot;Ping: stop&quot; ) </li></ul><ul><li>pong ! Stop </li></ul><ul><li>exit () </li></ul><ul><li>} </li></ul><ul><li>class Pong extends Actor { </li></ul><ul><li>def act () { </li></ul><ul><li>var pongCount = 0 </li></ul><ul><li>while ( true ) { </li></ul><ul><li>receive { </li></ul><ul><li>case Ping => </li></ul><ul><li>if ( pongCount % 1000 == 0 ) </li></ul><ul><li>Console . println ( &quot;Pong: ping &quot; + pongCount ) </li></ul><ul><li>sender ! Pong </li></ul><ul><li>pongCount = pongCount + 1 </li></ul><ul><li>case Stop => </li></ul><ul><li>Console . println ( &quot;Pong: stop&quot; ) </li></ul><ul><li>exit () </li></ul><ul><li>val pong = new Pong </li></ul><ul><li>val ping = new Ping ( 100000 , pong ) </li></ul><ul><li>ping . start </li></ul><ul><li>pong . start </li></ul><ul><li>With the advent of multi-core processors concurrent programming is becoming indispensable. </li></ul><ul><li>Actors are basically concurrent processes that communicate by exchanging messages, instead of sharing state. </li></ul>
  40. 40. Companion objects and Static <ul><li>Singleton and Static considered harmful </li></ul><ul><ul><li>Static methods cannot be polymorphic </li></ul></ul><ul><ul><li>Inheritance problems </li></ul></ul><ul><ul><li>So - all static members are now grouped in their own ‘object’ </li></ul></ul><ul><li>Scala’s “companion ‘object’” (singleton object) </li></ul>
  41. 41. More and more and more…. <ul><li>Nested Functions </li></ul><ul><li>By-name parameters </li></ul><ul><ul><li>Lazy evaluation </li></ul></ul><ul><ul><li>Logging – no more stupid ( if ( log.isEnabled() ) protection! ) </li></ul></ul><ul><li>Private packages </li></ul><ul><li>LiftWeb (Rails/Grails like web app for Scala) </li></ul><ul><li>The Option type – optional values – Some or None </li></ul><ul><li>First-class Properties coming… </li></ul><ul><ul><li>Properties are objects (OO sense) </li></ul></ul><ul><ul><li>Govern access to a (possibly calculated) field. </li></ul></ul><ul><ul><li>Properties can have other methods in addition to get/set logic, such as registering event listeners. </li></ul></ul><ul><li>Writing new control structures </li></ul><ul><li>val file = new File ( &quot;date.txt&quot; ) </li></ul><ul><li>withPrintWriter ( file ) { </li></ul><ul><li>writer => writer.println ( new java.util.Date ) </li></ul><ul><li>} </li></ul>
  42. 42. More Technologies are out there! <ul><li>Expand your mind! </li></ul><ul><li>Online Ajax HelpRequestList program in 9 lines!! </li></ul><ul><ul><li>Groovy on Grails </li></ul></ul><ul><li>Maven the modular build system Connoisseur! </li></ul><ul><li>Groovy Builder and G-Strings </li></ul><ul><ul><li>Groovy Command Line Interpreter </li></ul></ul><ul><ul><li>Groovy Wicket builder </li></ul></ul><ul><li>Polygot programming </li></ul><ul><ul><li>a computer program or script written in a valid form of multiple programming languages , which performs the same operations or output independently of the programming language used to compile or interpret it. </li></ul></ul><ul><li>Git </li></ul><ul><ul><li>a distributed revision control / software configuration management project created by Linus Torvalds , initially for the Linux kernel development. </li></ul></ul>
  43. 43. The Full Article <ul><li>Read the article at: </li></ul><ul><ul><li>http://stubbisms.wordpress.com/2008/02/22/my-foray-into-the-world-of-scala/ </li></ul></ul><ul><li>More Scala links </li></ul><ul><ul><li>scala-lang.org </li></ul></ul><ul><li>Thanks for listening! </li></ul>

×