SlideShare a Scribd company logo
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 :)

More Related Content

What's hot (19)

Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In Practice
Michiel Borkent
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
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: Notes
Roberto Casadei
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
Roberto 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 Hodorog
3Pillar Global
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Kotlin
KotlinKotlin
Kotlin
YeldosTanikin
 
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
Raúl Raja Martínez
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
Hiroshi Ono
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
Rémy-Christophe Schermesser
 
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 System
John De Goes
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi 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 Python
Anoop Thomas Mathew
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In Practice
Michiel 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: Notes
Roberto Casadei
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
Roberto 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 Hodorog
3Pillar Global
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus 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 Programmer
Raú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 System
John De Goes
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi 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 Python
Anoop Thomas Mathew
 

Viewers also liked (20)

Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012
Skills Matter Talks
 
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
Girish 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
 
Apache hive
Apache hiveApache hive
Apache hive
pradipbajpai68
 
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
 
Python to scala
Python to scalaPython to scala
Python to scala
kao kuo-tung
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
Mario Gleichmann
 
Indexed Hive
Indexed HiveIndexed Hive
Indexed Hive
NikhilDeshpande
 
Fun[ctional] spark with scala
Fun[ctional] spark with scalaFun[ctional] spark with scala
Fun[ctional] spark with scala
David Vallejo Navarro
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and Implementations
MICHRAFY 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 Scala
Alexander Dean
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebook
ragho
 
DataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopDataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL Workshop
Hakka Labs
 
Spark Meetup TensorFrames
Spark Meetup TensorFramesSpark Meetup TensorFrames
Spark Meetup TensorFrames
Jen 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 Cases
nzhang
 
A Basic Hive Inspection
A Basic Hive InspectionA Basic Hive Inspection
A Basic Hive Inspection
Linda Tillman
 
Functional Programming and Big Data
Functional Programming and Big DataFunctional Programming and Big Data
Functional Programming and Big Data
DataWorks Summit
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Spark Sql for Training
Spark Sql for TrainingSpark Sql for Training
Spark Sql for Training
Bryan 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 DataFrames
Databricks
 
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
Girish 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 Language
Mario Gleichmann
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and Implementations
MICHRAFY 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 Scala
Alexander Dean
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebook
ragho
 
DataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopDataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL Workshop
Hakka Labs
 
Spark Meetup TensorFrames
Spark Meetup TensorFramesSpark Meetup TensorFrames
Spark Meetup TensorFrames
Jen 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 Cases
nzhang
 
A Basic Hive Inspection
A Basic Hive InspectionA Basic Hive Inspection
A Basic Hive Inspection
Linda Tillman
 
Functional Programming and Big Data
Functional Programming and Big DataFunctional Programming and Big Data
Functional Programming and Big Data
DataWorks Summit
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Spark Sql for Training
Spark Sql for TrainingSpark Sql for Training
Spark Sql for Training
Bryan 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 DataFrames
Databricks
 
Ad

Similar to Functional Programming in Scala (20)

Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
datamantra
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Namuk Park
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
190030341 fcp lab 1
190030341  fcp lab 1190030341  fcp lab 1
190030341 fcp lab 1
madhukalyanchodisett
 
Functional Programming Essentials
Functional Programming EssentialsFunctional Programming Essentials
Functional Programming Essentials
Kelley Robinson
 
Scala functions
Scala functionsScala functions
Scala functions
Knoldus Inc.
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
Damian Jureczko
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Functional Programming in Scala in a Nutshell
Functional Programming in Scala in a NutshellFunctional Programming in Scala in a Nutshell
Functional Programming in Scala in a Nutshell
xxx nell
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
Sandip Kumar
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Scala
ScalaScala
Scala
Amir Payberah
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
Muhammad Fayyaz
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Scala
ScalaScala
Scala
Marcelo Cure
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
Fangda Wang
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
datamantra
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Namuk Park
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
Functional Programming Essentials
Functional Programming EssentialsFunctional Programming Essentials
Functional Programming Essentials
Kelley Robinson
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
Damian Jureczko
 
Functional Programming in Scala in a Nutshell
Functional Programming in Scala in a NutshellFunctional Programming in Scala in a Nutshell
Functional Programming in Scala in a Nutshell
xxx nell
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
Fangda Wang
 
Ad

Recently uploaded (20)

ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
GIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of UtilitiesGIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of Utilities
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
GIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of UtilitiesGIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of Utilities
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 

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 :)