SlideShare une entreprise Scribd logo
1  sur  62
Télécharger pour lire hors ligne
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Functional Programming in
Bassam Abd El-Hamid
@MrBassam
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Von Neumann architecture
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Von Neumann bottleneck
“Can Programming be Liberated from the von Neumann
Style?”
John Backus 1977
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
History of FP languages
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
A formal system in mathematical logic and
computer science for expressing computation by
way of variable binding and substitution
λ-calculus
http://en.wikipedia.org/wiki/Lambda_calculus
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
* Referential transparency
* No side effect
* Remove unused expression safely
Pure functions
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Scalable Language
Martin Odersky
2003
www.scala-lang.org
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Why Scala?
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Object-Oriented
Functional
Statically Typed
Runs on the JVM
Can Execute Java Code
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
All types are objects
Type inference.
Nested Functions.
Functions are objects.
Domain specific language (DSL) support
Traits.
Closures.
Concurrency support inspired by Erlang.
vs Java
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Who is using Scala?
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Who is using Scala?
And more ...
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Links:
Who's using Scala? (March, 2013)
http://alvinalexander.com/scala/whos-using-scala-akka-play-framework
Scala Adoption by Enterprises
http://www.slideshare.net/mslinn/scala-adoption-by-enterprises
Scala in the Enterprise
http://www.scala-lang.org/node/1658
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Syntax
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
// This is a valid comment
/* This is a multiline
comment */
Comments:
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}
Hello, world!
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
val s = "hello" // ; not requierd
println(s)
val s = "hello"; println(s) // ; is REQUIRED
Newline Characters
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Keywords
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
package com.bassam.stuff
// Import one class
import scala.collection.mutable.HashMap
// Import more than one
import scala.collection.immutable.{TreeMap, TreeSet}
// Import all
import scala.xml._
Scala Packages
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
var 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 Scala
Data Types (the same data types as Java)
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
Classes, Objects and Traits
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("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 = zc
def move(dx: Int, dy: Int, dz: Int) {
x = x + dx
y = y + dy
z = z + dz
println ("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 Scala
trait someTrait {
var somevar: Int=0
def someFun(x: Int): Int = (x*2)/5
}
trait anotherTrait {
var anothervar: Int=0
def anotherFun(x: Int): Int = (x*7)/100
}
class class1(){}
class class2() extends class1 with someTrait with
anotherTrait
{}
Classes, Objects and Traits
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
private visible only inside the class or object
protected only accessible from subclasses
public accessed from anywhere (Default)
protected[UpToScope]
private[UpToScpoe]
Access Modifiers
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
if(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 is
true.
}
IF...ELSE
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
while(condition){
statement(s);
}
do{
statement(s);
}while( condition );
for( x <- Range ){
statement(s);
}
Loop Types
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
import scala.util.control.Breaks
...
var x:Int=1
val brk=new Breaks
brk.breakable{
while( x>0 ){
if (x==10) brk.break
print(x)
x=x+1
}}
break a loop
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}
def sum(x:Int,z:Int):Int=z+x
def pi=3.14
Sum(5,6) //11
Functions
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def v:Int=5*6
def sum(x: => Int,z:Int):Int=z+x
sum(v,5) //35
Functions Call-by-Name
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def sum(x: Int,z: Int):Int=z+x
sum(z=5,x=6)
Functions with Named Arguments
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def sum( nums : Int* ) :Int ={
var buf:Int=0
for( i <- nums) buf=buf+i
}
sum(5,2,74,....)
Function with Variable Arguments
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def sum( a:Int=5, b:Int=7 ) : Int = {
var s:Int = 0
s = a + b
return s
}
Default Parameter Values for a Function
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def factorial(i: Int): Int = {
def fact(i: Int, accumulator: Int): Int = {
if (i <= 1)
accumulator
else
fact(i - 1, i * accumulator)
}
fact(i, 1)
}
Nested Functions - local functions
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def factorial(n: BigInt): BigInt = {
if (n <= 1)
1
else
n * factorial(n - 1)
}
Recursion Functions
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
object Test {
def main(args: Array[String]) {
val date = new Date
log(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 Scala
object 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 body
object Test {
var sum=(x:Int,z:Int) => x+z
def main(args: Array[String]) {
println(sum(5,6))
}
}
Anonymous Functions
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
object 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 Scala
val multiplier = (i:Int) => i * 10
val multiplier = (i:Int) => i * factor
var factor = 3
val multiplier = (i:Int) => i * factor
Closures
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Currying transforms a function that takes multiple
parameters into a chain of functions, each taking
a single parameter
Currying Functions schönfinkeling
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def strcat(s1: String,s2: String) = s1 + s2
def strcat(s1: String) = (s2: String) => s1 + s2
def main(args: Array[String]){
print (strcat ("Hello ")("World"))
}
Currying Functions schönfinkeling
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
def sum(x: Int,z: Int) = x + z
def 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 Scala
object 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 Scala
object 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" => 2
case y: Int => "scala.Int"
case _ => "many"
}
}
Pattern Matching
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
object 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("Hi
Alice!")
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 Scala
var x:Array[String] = new Array[String](3)
//or
var z = new Array[String](3)
Arrays
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
var x:Array[String] = new Array[String](3)
//or
var x = new Array[String](3)
//or
var x = Array("One", "Two", "Three")
x(0)="One" ; x(1)="Two" ; x(2)="Three"
Arrays
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
var myMatrix = Array.ofDim[Int](3,3)
myMatrix(0)(1)=10
Multi-Dimensional Arrays
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
var 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 Scala
var a=(0 to 10) //from 0 to 10
var b=(0 until 10) //from 0 to 9
var c=(0 to 10 by 2) // step 2
ranges
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
// List of Strings
val fruit: List[String] = List("apples", "oranges",
"pears")
// List of Integers
val nums: List[Int] = List(1, 2, 3, 4)
// Empty List.
val empty: List[Nothing] = List()
// Two dimensional list
val 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 Integers
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
// Empty List.
val empty = Nil
// Two dimensional list
val 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 type
var s : Set[Int] = Set()
// Set of integer type
var s : Set[Int] = Set(1,3,5,7)
//or
var s = Set(1,3,5,7)
Sets
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
/*Empty hash table whose keys are strings and
values 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 Scala
val tup = (1, "hello", Console)
//Which is syntactic sugar for:
val t = new Tuple3(1, "hello", Console)
val sum = t._1 + t._2 + t._3
t.productIterator.foreach{ i =>println("Value = " +
i )}
Tuples
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
object 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 Scala
object 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 Scala
import scala.util.matching.Regex
object Test {
def main(args: Array[String]) {
val pattern = "Scala".r
val str = "Scala is Scalable and cool"
println(pattern findFirstIn str)
}
}
Regular Expressions
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object 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 Scala
Questions
CAIRO TECH CLUB SESSION 5: Functional Programming in Scala
Thank you :)

Contenu connexe

Tendances

Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in ScalaShai Yallin
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In PracticeMichiel Borkent
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: NotesRoberto Casadei
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in ScalaRoberto Casadei
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako, Vasil Remeniuk
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemJohn De Goes
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdasshinolajla
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 

Tendances (19)

Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In Practice
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Kotlin
KotlinKotlin
Kotlin
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic Programmer
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 

En vedette

Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmerGirish Kumar A L
 
Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Denny Lee
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Databricks
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable LanguageMario Gleichmann
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsMICHRAFY MUSTAFA
 
Scala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in ScalaScala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in ScalaAlexander Dean
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebookragho
 
DataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopDataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopHakka Labs
 
Spark Meetup TensorFrames
Spark Meetup TensorFramesSpark Meetup TensorFrames
Spark Meetup TensorFramesJen Aman
 
Hive Training -- Motivations and Real World Use Cases
Hive Training -- Motivations and Real World Use CasesHive Training -- Motivations and Real World Use Cases
Hive Training -- Motivations and Real World Use Casesnzhang
 
A Basic Hive Inspection
A Basic Hive InspectionA Basic Hive Inspection
A Basic Hive InspectionLinda Tillman
 
Functional Programming and Big Data
Functional Programming and Big DataFunctional Programming and Big Data
Functional Programming and Big DataDataWorks Summit
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Spark Sql for Training
Spark Sql for TrainingSpark Sql for Training
Spark Sql for TrainingBryan Yang
 
Beyond SQL: Speeding up Spark with DataFrames
Beyond SQL: Speeding up Spark with DataFramesBeyond SQL: Speeding up Spark with DataFrames
Beyond SQL: Speeding up Spark with DataFramesDatabricks
 

En vedette (20)

Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
 
Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)
 
Apache hive
Apache hiveApache hive
Apache hive
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
 
Indexed Hive
Indexed HiveIndexed Hive
Indexed Hive
 
Fun[ctional] spark with scala
Fun[ctional] spark with scalaFun[ctional] spark with scala
Fun[ctional] spark with scala
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and Implementations
 
Scala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in ScalaScala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in Scala
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebook
 
DataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopDataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL Workshop
 
Spark Meetup TensorFrames
Spark Meetup TensorFramesSpark Meetup TensorFrames
Spark Meetup TensorFrames
 
Hive Training -- Motivations and Real World Use Cases
Hive Training -- Motivations and Real World Use CasesHive Training -- Motivations and Real World Use Cases
Hive Training -- Motivations and Real World Use Cases
 
A Basic Hive Inspection
A Basic Hive InspectionA Basic Hive Inspection
A Basic Hive Inspection
 
Functional Programming and Big Data
Functional Programming and Big DataFunctional Programming and Big Data
Functional Programming and Big Data
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Spark Sql for Training
Spark Sql for TrainingSpark Sql for Training
Spark Sql for Training
 
Beyond SQL: Speeding up Spark with DataFrames
Beyond SQL: Speeding up Spark with DataFramesBeyond SQL: Speeding up Spark with DataFrames
Beyond SQL: Speeding up Spark with DataFrames
 

Similaire à Functional Programming in Scala

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsPeter Pilgrim
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaVasil Remeniuk
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»e-Legion
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffJAX London
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to ScalaRiccardo Cardin
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in ScalaRadim Pavlicek
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 

Similaire à Functional Programming in Scala (20)

Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
SCALA - Functional domain
SCALA -  Functional domainSCALA -  Functional domain
SCALA - Functional domain
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala apps
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 

Dernier

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Dernier (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Functional Programming in Scala

  • 1. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Functional Programming in Bassam Abd El-Hamid @MrBassam
  • 2. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Von Neumann architecture
  • 3. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Von Neumann bottleneck “Can Programming be Liberated from the von Neumann Style?” John Backus 1977
  • 4. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala History of FP languages
  • 5. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala A formal system in mathematical logic and computer science for expressing computation by way of variable binding and substitution λ-calculus http://en.wikipedia.org/wiki/Lambda_calculus
  • 6. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala * Referential transparency * No side effect * Remove unused expression safely Pure functions
  • 7. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Scalable Language Martin Odersky 2003 www.scala-lang.org
  • 8. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Why Scala?
  • 9. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Object-Oriented Functional Statically Typed Runs on the JVM Can Execute Java Code
  • 10. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala All types are objects Type inference. Nested Functions. Functions are objects. Domain specific language (DSL) support Traits. Closures. Concurrency support inspired by Erlang. vs Java
  • 11. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Who is using Scala?
  • 12. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Who is using Scala? And more ...
  • 13. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Links: Who's using Scala? (March, 2013) http://alvinalexander.com/scala/whos-using-scala-akka-play-framework Scala Adoption by Enterprises http://www.slideshare.net/mslinn/scala-adoption-by-enterprises Scala in the Enterprise http://www.scala-lang.org/node/1658
  • 14. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Syntax
  • 15. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala // This is a valid comment /* This is a multiline comment */ Comments:
  • 16. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } } Hello, world!
  • 17. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala val s = "hello" // ; not requierd println(s) val s = "hello"; println(s) // ; is REQUIRED Newline Characters
  • 18. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Keywords
  • 19. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala package com.bassam.stuff // Import one class import scala.collection.mutable.HashMap // Import more than one import scala.collection.immutable.{TreeMap, TreeSet} // Import all import scala.xml._ Scala Packages
  • 20. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala var 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Data Types (the same data types as Java)
  • 22. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala class Point(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy println ("Point x location : " + x); println ("Point y location : " + y); } } Classes, Objects and Traits
  • 23. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy println ("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 = zc def move(dx: Int, dy: Int, dz: Int) { x = x + dx y = y + dy z = z + dz println ("Point x location : " + x); println ("Point y location : " + y); println ("Point z location : " + z); }} Classes, Objects and Traits
  • 24. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala trait someTrait { var somevar: Int=0 def someFun(x: Int): Int = (x*2)/5 } trait anotherTrait { var anothervar: Int=0 def anotherFun(x: Int): Int = (x*7)/100 } class class1(){} class class2() extends class1 with someTrait with anotherTrait {} Classes, Objects and Traits
  • 25. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala private visible only inside the class or object protected only accessible from subclasses public accessed from anywhere (Default) protected[UpToScope] private[UpToScpoe] Access Modifiers
  • 26. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala if(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 is true. } IF...ELSE
  • 27. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala while(condition){ statement(s); } do{ statement(s); }while( condition ); for( x <- Range ){ statement(s); } Loop Types
  • 28. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala import scala.util.control.Breaks ... var x:Int=1 val brk=new Breaks brk.breakable{ while( x>0 ){ if (x==10) brk.break print(x) x=x+1 }} break a loop
  • 29. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def functionName ([list of parameters]) : [return type] = { function body return [expr] } def sum(x:Int,z:Int):Int=z+x def pi=3.14 Sum(5,6) //11 Functions
  • 30. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def v:Int=5*6 def sum(x: => Int,z:Int):Int=z+x sum(v,5) //35 Functions Call-by-Name
  • 31. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def sum(x: Int,z: Int):Int=z+x sum(z=5,x=6) Functions with Named Arguments
  • 32. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def sum( nums : Int* ) :Int ={ var buf:Int=0 for( i <- nums) buf=buf+i } sum(5,2,74,....) Function with Variable Arguments
  • 33. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def sum( a:Int=5, b:Int=7 ) : Int = { var s:Int = 0 s = a + b return s } Default Parameter Values for a Function
  • 34. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def factorial(i: Int): Int = { def fact(i: Int, accumulator: Int): Int = { if (i <= 1) accumulator else fact(i - 1, i * accumulator) } fact(i, 1) } Nested Functions - local functions
  • 35. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def factorial(n: BigInt): BigInt = { if (n <= 1) 1 else n * factorial(n - 1) } Recursion Functions
  • 36. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object Test { def main(args: Array[String]) { val date = new Date log(date, "message1" ) log(date, "message2" ) log(date, "message3" ) } def log(date: Date, message: String) = { println(date + "----" + message) } } Partially Applied Functions
  • 37. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala ([list of parameters]) => function body object Test { var sum=(x:Int,z:Int) => x+z def main(args: Array[String]) { println(sum(5,6)) } } Anonymous Functions
  • 39. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala val multiplier = (i:Int) => i * 10 val multiplier = (i:Int) => i * factor var factor = 3 val multiplier = (i:Int) => i * factor Closures
  • 41. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter Currying Functions schönfinkeling
  • 42. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def strcat(s1: String,s2: String) = s1 + s2 def strcat(s1: String) = (s2: String) => s1 + s2 def main(args: Array[String]){ print (strcat ("Hello ")("World")) } Currying Functions schönfinkeling
  • 43. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala def sum(x: Int,z: Int) = x + z def main(args: Array[String]){ val sumCurried = Function.curried(sum _) print (sumCurried(5)(6)) } Currying Functions schönfinkeling
  • 44. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object 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" => 2 case y: Int => "scala.Int" case _ => "many" } } Pattern Matching
  • 46. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object 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("Hi Alice!") 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala var x:Array[String] = new Array[String](3) //or var z = new Array[String](3) Arrays
  • 48. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala var x:Array[String] = new Array[String](3) //or var x = new Array[String](3) //or var x = Array("One", "Two", "Three") x(0)="One" ; x(1)="Two" ; x(2)="Three" Arrays
  • 49. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala var myMatrix = Array.ofDim[Int](3,3) myMatrix(0)(1)=10 Multi-Dimensional Arrays
  • 50. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala var 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala var a=(0 to 10) //from 0 to 10 var b=(0 until 10) //from 0 to 9 var c=(0 to 10 by 2) // step 2 ranges
  • 52. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala // List of Strings val fruit: List[String] = List("apples", "oranges", "pears") // List of Integers val nums: List[Int] = List(1, 2, 3, 4) // Empty List. val empty: List[Nothing] = List() // Two dimensional list val dim: List[List[Int]] = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) Lists
  • 53. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala // List of Integers val nums = 1 :: (2 :: (3 :: (4 :: Nil))) // Empty List. val empty = Nil // Two dimensional list val dim = (1 :: (0 :: (0 :: Nil))) :: (0 :: (1 :: (0 :: Nil))) :: (0 :: (0 :: (1 :: Nil))) :: Nil } } Lists
  • 54. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala // Empty set of integer type var s : Set[Int] = Set() // Set of integer type var s : Set[Int] = Set(1,3,5,7) //or var s = Set(1,3,5,7) Sets
  • 55. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala /*Empty hash table whose keys are strings and values 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala val tup = (1, "hello", Console) //Which is syntactic sugar for: val t = new Tuple3(1, "hello", Console) val sum = t._1 + t._2 + t._3 t.productIterator.foreach{ i =>println("Value = " + i )} Tuples
  • 57. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object Test { def main(args: Array[String]) { val it = Iterator("a", "number", "of", "words") while (it.hasNext){ println(it.next()) } } } Iterators
  • 58. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala object 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala import scala.util.matching.Regex object Test { def main(args: Array[String]) { val pattern = "Scala".r val str = "Scala is Scalable and cool" println(pattern findFirstIn str) } } Regular Expressions
  • 60. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object 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. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Questions
  • 62. CAIRO TECH CLUB SESSION 5: Functional Programming in Scala Thank you :)