Functional Programming in Scala
Upcoming SlideShare
Loading in...5
×
 

Functional Programming in Scala

on

  • 1,360 views

CAIRO TECH CLUB SESSION 5: Functional Programming in Scala

CAIRO TECH CLUB SESSION 5: Functional Programming in Scala

Statistics

Views

Total Views
1,360
Views on SlideShare
1,359
Embed Views
1

Actions

Likes
5
Downloads
55
Comments
0

1 Embed 1

https://duckduckgo.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Functional Programming in Scala Functional Programming in Scala Presentation Transcript

    • 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 NeumannStyle?”John Backus 1977
    • 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 expressing computation byway of variable binding and substitutionλ-calculushttp://en.wikipedia.org/wiki/Lambda_calculus
    • CAIRO TECH CLUB SESSION 5: Functional Programming in Scala* Referential transparency* No side effect* Remove unused expression safelyPure functions
    • 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 Execute Java Code
    • 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
    • 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/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
    • 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 */Comments:
    • CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaobject HelloWorld {def main(args: Array[String]) {println("Hello, world!")}}Hello, world!
    • CAIRO TECH CLUB SESSION 5: Functional Programming in Scalaval s = "hello" // ; not requierdprintln(s)val s = "hello"; println(s) // ; is REQUIREDNewline Characters
    • 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.collection.mutable.HashMap// Import more than oneimport scala.collection.immutable.{TreeMap, TreeSet}// Import allimport scala.xml._Scala Packages
    • 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
    • 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 move(dx: Int, dy: Int) {x = x + dxy = y + dyprintln ("Point x location : " + x);println ("Point y location : " + y);}}Classes, Objects and Traits
    • 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
    • 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
    • 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
    • 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
    • CAIRO TECH CLUB SESSION 5: Functional Programming in Scalawhile(condition){statement(s);}do{statement(s);}while( condition );for( x <- Range ){statement(s);}Loop Types
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • CAIRO TECH CLUB SESSION 5: Functional Programming in Scaladef factorial(n: BigInt): BigInt = {if (n <= 1)1elsen * factorial(n - 1)}Recursion Functions
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar x:Array[String] = new Array[String](3)//orvar z = new Array[String](3)Arrays
    • 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
    • CAIRO TECH CLUB SESSION 5: Functional Programming in Scalavar myMatrix = Array.ofDim[Int](3,3)myMatrix(0)(1)=10Multi-Dimensional Arrays
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaQuestions
    • CAIRO TECH CLUB SESSION 5: Functional Programming in ScalaThank you :)