0
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaFunctional Programming inBassam Abd El-Hamid@MrBassam
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaVon Neumann architecture
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaVon Neumann bottleneck“Can Programming be Liberated from the von...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaHistory of FP languages
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaA formal system in mathematical logic andcomputer science for ex...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala* Referential transparency* No side effect* Remove unused expres...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaScalable LanguageMartin Odersky2003www.scala-lang.org
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaWhy Scala?
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaObject-OrientedFunctionalStatically TypedRuns on the JVMCan Exec...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaAll types are objectsType inference.Nested Functions.Functions a...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaWho is using Scala?
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaWho is using Scala?And more ...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaLinks:Whos using Scala? (March, 2013)http://alvinalexander.com/s...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaSyntax
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala// This is a valid comment/* This is a multilinecomment */Commen...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject HelloWorld {def main(args: Array[String]) {println("Hello...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaval s = "hello" // ; not requierdprintln(s)val s = "hello"; prin...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaKeywords
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalapackage com.bassam.stuff// Import one classimport scala.collecti...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar or val VariableName : DataType [= Initial Value]var myVar : ...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaData Types (the same data types as Java)
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaclass Point(xc: Int, yc: Int) {var x: Int = xcvar y: Int = ycdef...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaclass Point(val xc: Int, val yc: Int) {var x: Int = xcvar y: Int...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalatrait someTrait {var somevar: Int=0def someFun(x: Int): Int = (x...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaprivate visible only inside the class or objectprotected only ac...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaif(Boolean_expression 1){//Executes when the Boolean expression ...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalawhile(condition){statement(s);}do{statement(s);}while( condition...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaimport scala.util.control.Breaks...var x:Int=1val brk=new Breaks...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef functionName ([list of parameters]) : [return type] = {funct...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef v:Int=5*6def sum(x: => Int,z:Int):Int=z+xsum(v,5) //35Functi...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef sum(x: Int,z: Int):Int=z+xsum(z=5,x=6)Functions with Named A...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef sum( nums : Int* ) :Int ={var buf:Int=0for( i <- nums) buf=b...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef sum( a:Int=5, b:Int=7 ) : Int = {var s:Int = 0s = a + bretur...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef factorial(i: Int): Int = {def fact(i: Int, accumulator: Int)...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef factorial(n: BigInt): BigInt = {if (n <= 1)1elsen * factoria...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {val date = new Datel...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {val logWithDateBound...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala([list of parameters]) => function bodyobject Test {var sum=(x:I...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {println( apply( layo...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaval multiplier = (i:Int) => i * 10val multiplier = (i:Int) => i ...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaCurrying transforms a function that takes multipleparameters int...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef strcat(s1: String,s2: String) = s1 + s2def strcat(s1: String...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef sum(x: Int,z: Int) = x + zdef main(args: Array[String]){val ...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {println(matchTest(3)...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {println(matchTest("t...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {val alice = new Pers...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar x:Array[String] = new Array[String](3)//orvar z = new Array[...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar x:Array[String] = new Array[String](3)//orvar x = new Array[...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar myMatrix = Array.ofDim[Int](3,3)myMatrix(0)(1)=10Multi-Dimen...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar myArr1 = Array(1.9, 2.9, 3.4, 3.5)var myArr2 = Array(8.9, 7....
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar a=(0 to 10) //from 0 to 10var b=(0 until 10) //from 0 to 9va...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala// List of Stringsval fruit: List[String] = List("apples", "oran...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala// List of Integersval nums = 1 :: (2 :: (3 :: (4 :: Nil)))// Em...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala// Empty set of integer typevar s : Set[Int] = Set()// Set of in...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala/*Empty hash table whose keys are strings andvalues are integers...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaval tup = (1, "hello", Console)//Which is syntactic sugar for:va...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {val it = Iterator("a...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def findPerson(key: Int): Option[Person]def main(ar...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaimport scala.util.matching.Regexobject Test {def main(args: Arra...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaimport java.io.FileReaderimport java.io.FileNotFoundExceptionimp...
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaQuestions
CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaThank you :)
Upcoming SlideShare
Loading in...5
×

Functional Programming in Scala

1,534

Published on

CAIRO TECH CLUB SESSION 5: Functional Programming in Scala

Published in: Technology
0 Comments
8 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,534
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
73
Comments
0
Likes
8
Embeds 0
No embeds

No notes for slide

Transcript of "Functional Programming in Scala"

  1. 1. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaFunctional Programming inBassam Abd El-Hamid@MrBassam
  2. 2. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaVon Neumann architecture
  3. 3. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaVon Neumann bottleneck“Can Programming be Liberated from the von NeumannStyle?”John Backus 1977
  4. 4. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaHistory of FP languages
  5. 5. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaA formal system in mathematical logic andcomputer science for expressing computation byway of variable binding and substitutionλ-calculushttp://en.wikipedia.org/wiki/Lambda_calculus
  6. 6. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala* Referential transparency* No side effect* Remove unused expression safelyPure functions
  7. 7. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaScalable LanguageMartin Odersky2003www.scala-lang.org
  8. 8. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaWhy Scala?
  9. 9. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaObject-OrientedFunctionalStatically TypedRuns on the JVMCan Execute Java Code
  10. 10. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaAll types are objectsType inference.Nested Functions.Functions are objects.Domain specific language (DSL) supportTraits.Closures.Concurrency support inspired by Erlang.vs Java
  11. 11. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaWho is using Scala?
  12. 12. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaWho is using Scala?And more ...
  13. 13. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaLinks:Whos using Scala? (March, 2013)http://alvinalexander.com/scala/whos-using-scala-akka-play-frameworkScala Adoption by Enterpriseshttp://www.slideshare.net/mslinn/scala-adoption-by-enterprisesScala in the Enterprisehttp://www.scala-lang.org/node/1658
  14. 14. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaSyntax
  15. 15. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala// This is a valid comment/* This is a multilinecomment */Comments:
  16. 16. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject HelloWorld {def main(args: Array[String]) {println("Hello, world!")}}Hello, world!
  17. 17. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaval s = "hello" // ; not requierdprintln(s)val s = "hello"; println(s) // ; is REQUIREDNewline Characters
  18. 18. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaKeywords
  19. 19. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalapackage com.bassam.stuff// Import one classimport scala.collection.mutable.HashMap// Import more than oneimport scala.collection.immutable.{TreeMap, TreeSet}// Import allimport scala.xml._Scala Packages
  20. 20. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar or val VariableName : DataType [= Initial Value]var myVar : String = "mutable variable"val myVal : String = "immutable variable"//Multiple assignments:val (myVar1: Int, myVar2: String) = Pair(5, "Foo")Variable Declaration
  21. 21. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaData Types (the same data types as Java)
  22. 22. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaclass Point(xc: Int, yc: Int) {var x: Int = xcvar y: Int = ycdef move(dx: Int, dy: Int) {x = x + dxy = y + dyprintln ("Point x location : " + x);println ("Point y location : " + y);}}Classes, Objects and Traits
  23. 23. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaclass Point(val xc: Int, val yc: Int) {var x: Int = xcvar y: Int = ycdef move(dx: Int, dy: Int) {x = x + dxy = y + dyprintln ("Point x location : " + x);println ("Point y location : " + y);}}class Location(override val xc: Int, override val yc: Int,val zc :Int) extends Point(xc, yc){var z: Int = zcdef move(dx: Int, dy: Int, dz: Int) {x = x + dxy = y + dyz = z + dzprintln ("Point x location : " + x);println ("Point y location : " + y);println ("Point z location : " + z);}}Classes, Objects and Traits
  24. 24. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalatrait someTrait {var somevar: Int=0def someFun(x: Int): Int = (x*2)/5}trait anotherTrait {var anothervar: Int=0def anotherFun(x: Int): Int = (x*7)/100}class class1(){}class class2() extends class1 with someTrait withanotherTrait{}Classes, Objects and Traits
  25. 25. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaprivate visible only inside the class or objectprotected only accessible from subclassespublic accessed from anywhere (Default)protected[UpToScope]private[UpToScpoe]Access Modifiers
  26. 26. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaif(Boolean_expression 1){//Executes when the Boolean expression 1 is true}else if(Boolean_expression 2){//Executes when the Boolean expression 2 is true}else if(Boolean_expression 3){//Executes when the Boolean expression 3 is true}else {//Executes when the none of the above condition istrue.}IF...ELSE
  27. 27. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalawhile(condition){statement(s);}do{statement(s);}while( condition );for( x <- Range ){statement(s);}Loop Types
  28. 28. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaimport scala.util.control.Breaks...var x:Int=1val brk=new Breaksbrk.breakable{while( x>0 ){if (x==10) brk.breakprint(x)x=x+1}}break a loop
  29. 29. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef functionName ([list of parameters]) : [return type] = {function bodyreturn [expr]}def sum(x:Int,z:Int):Int=z+xdef pi=3.14Sum(5,6) //11Functions
  30. 30. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef v:Int=5*6def sum(x: => Int,z:Int):Int=z+xsum(v,5) //35Functions Call-by-Name
  31. 31. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef sum(x: Int,z: Int):Int=z+xsum(z=5,x=6)Functions with Named Arguments
  32. 32. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef sum( nums : Int* ) :Int ={var buf:Int=0for( i <- nums) buf=buf+i}sum(5,2,74,....)Function with Variable Arguments
  33. 33. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef sum( a:Int=5, b:Int=7 ) : Int = {var s:Int = 0s = a + breturn s}Default Parameter Values for a Function
  34. 34. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef factorial(i: Int): Int = {def fact(i: Int, accumulator: Int): Int = {if (i <= 1)accumulatorelsefact(i - 1, i * accumulator)}fact(i, 1)}Nested Functions - local functions
  35. 35. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef factorial(n: BigInt): BigInt = {if (n <= 1)1elsen * factorial(n - 1)}Recursion Functions
  36. 36. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {val date = new Datelog(date, "message1" )log(date, "message2" )log(date, "message3" )}def log(date: Date, message: String) = {println(date + "----" + message)}}Partially Applied Functions
  37. 37. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {val logWithDateBound = log(new Date, _ : String)logWithDateBound("message1" )logWithDateBound("message2" )logWithDateBound("message3" )}def log(date: Date, message: String) = {println(date + "----" + message)}}Partially Applied Functions
  38. 38. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala([list of parameters]) => function bodyobject Test {var sum=(x:Int,z:Int) => x+zdef main(args: Array[String]) {println(sum(5,6))}}Anonymous Functions
  39. 39. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {println( apply( layout, 10) )}def apply(f: Int => String, v: Int) = f(v)def layout[A](x: A) = "[" + x.toString() + "]"}Higher-Order Functions
  40. 40. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaval multiplier = (i:Int) => i * 10val multiplier = (i:Int) => i * factorvar factor = 3val multiplier = (i:Int) => i * factorClosures
  41. 41. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaCurrying transforms a function that takes multipleparameters into a chain of functions, each takinga single parameterCurrying Functions schönfinkeling
  42. 42. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef strcat(s1: String,s2: String) = s1 + s2def strcat(s1: String) = (s2: String) => s1 + s2def main(args: Array[String]){print (strcat ("Hello ")("World"))}Currying Functions schönfinkeling
  43. 43. CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef sum(x: Int,z: Int) = x + zdef main(args: Array[String]){val sumCurried = Function.curried(sum _)print (sumCurried(5)(6))}Currying Functions schönfinkeling
  44. 44. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {println(matchTest(3))}def matchTest(x: Int): String = x match {case 1 => "one"case 2 => "two"case _ => "many"}}Pattern Matching
  45. 45. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {println(matchTest("two"))println(matchTest("test"))println(matchTest(1))}def matchTest(x: Any): Any = x match {case 1 => "one"case "two" => 2case y: Int => "scala.Int"case _ => "many"}}Pattern Matching
  46. 46. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {val alice = new Person("Alice", 25)val bob = new Person("Bob", 32)val charlie = new Person("Charlie", 32)for (person <- List(alice, bob, charlie)) {person match {case Person("Alice", 25) => println("HiAlice!")case Person("Bob", 32) => println("Hi Bob!")case Person(name, age) =>println("Age: " + age + " year, name: " +name + "?")}}}// case class, empty one.case class Person(name: String, age: Int)}Pattern Matching
  47. 47. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar x:Array[String] = new Array[String](3)//orvar z = new Array[String](3)Arrays
  48. 48. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar x:Array[String] = new Array[String](3)//orvar x = new Array[String](3)//orvar x = Array("One", "Two", "Three")x(0)="One" ; x(1)="Two" ; x(2)="Three"Arrays
  49. 49. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar myMatrix = Array.ofDim[Int](3,3)myMatrix(0)(1)=10Multi-Dimensional Arrays
  50. 50. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar myArr1 = Array(1.9, 2.9, 3.4, 3.5)var myArr2 = Array(8.9, 7.9, 0.4, 1.5)var myArr3 = Array.concat( myArr1, myArr2)Arrays
  51. 51. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar a=(0 to 10) //from 0 to 10var b=(0 until 10) //from 0 to 9var c=(0 to 10 by 2) // step 2ranges
  52. 52. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala// List of Stringsval fruit: List[String] = List("apples", "oranges","pears")// List of Integersval nums: List[Int] = List(1, 2, 3, 4)// Empty List.val empty: List[Nothing] = List()// Two dimensional listval dim: List[List[Int]] =List(List(1, 0, 0),List(0, 1, 0),List(0, 0, 1))Lists
  53. 53. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala// List of Integersval nums = 1 :: (2 :: (3 :: (4 :: Nil)))// Empty List.val empty = Nil// Two dimensional listval dim = (1 :: (0 :: (0 :: Nil))) ::(0 :: (1 :: (0 :: Nil))) ::(0 :: (0 :: (1 :: Nil))) :: Nil}}Lists
  54. 54. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala// Empty set of integer typevar s : Set[Int] = Set()// Set of integer typevar s : Set[Int] = Set(1,3,5,7)//orvar s = Set(1,3,5,7)Sets
  55. 55. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala/*Empty hash table whose keys are strings andvalues are integers:*/var A:Map[Char,Int] = Map()// A map with keys and values.val colors = Map("red" -> "#FF0000", "azure" ->"#F0FFFF")Maps / Hash tables
  56. 56. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaval tup = (1, "hello", Console)//Which is syntactic sugar for:val t = new Tuple3(1, "hello", Console)val sum = t._1 + t._2 + t._3t.productIterator.foreach{ i =>println("Value = " +i )}Tuples
  57. 57. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def main(args: Array[String]) {val it = Iterator("a", "number", "of", "words")while (it.hasNext){println(it.next())}}}Iterators
  58. 58. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject Test {def findPerson(key: Int): Option[Person]def main(args: Array[String]) {val capitals = Map("France" -> "Paris", "Japan"-> "Tokyo")println("capitals.get( "France" ) : " +capitals.get( "France" ))println("capitals.get( "India" ) : " +capitals.get( "India" ))}}Options
  59. 59. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaimport scala.util.matching.Regexobject Test {def main(args: Array[String]) {val pattern = "Scala".rval str = "Scala is Scalable and cool"println(pattern findFirstIn str)}}Regular Expressions
  60. 60. CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaimport java.io.FileReaderimport java.io.FileNotFoundExceptionimport java.io.IOExceptionobject Test {def main(args: Array[String]) {try {val f = new FileReader("input.txt")} catch {case ex: FileNotFoundException =>>{println("Missing file exception")}case ex: IOException => {println("IO Exception")}}}}Exception Handling
  61. 61. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaQuestions
  62. 62. CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaThank you :)
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×