SlideShare ist ein Scribd-Unternehmen logo
1 von 49
Principles of Functional
Progrmming in Scala
• Moor’s Law
• Clock frequency
has not raised.
• More Complex
programs.
• Growing in data
Cuncurrency and Parallelism

non-determinism
Interference
Horizontal-scaling
among vertical-scaling
Example

var x = 0
async{ x = x+1 }
async{ x = x*2 }
// the answer could be 0, 1 or 2
Non-determinism = parallel processing+ mutable values
Paradigm

In science, a paradigm describes distinct concepts or
thought patterns in some scientific discipline.
Main programming paradigms:
imperative programming
functional programming
logic programming
Imparative paradigm

modifying mutable variables,
using assignments
and control structures such as if-thenelse, loops, break, continue, return.
Fucntional Paradigm

Immutable states
Functions without side-effects
Everything is function
Functions are expressions not statements
Referential transparency

once a variable is given a value it never changes.
no side effects are possible.
Functions are building blocks  functions are free side-effect
function call does not affect other functions and it just computes its
own output for a specific input
sin (pi) = 0
Functions are expressions not statements
FP is inspired by mathematics

Neither theories nor functions have mutable values.
You can combine functions to make more complex functions
The result of a function or a theory does not change for different input.
(a+b)^2 = a^2 + b^2 + 2*a*b
This state doesn’t change for different inputs.
Functional Languages

Pure(restricted) Functional languages ( no imperative structure)
like: Pure Lisp, XSLT, XPath, XQuery, FP,Haskell (without I/O Monad or
UnsafePerformIO)
Wider sense : Lisp, Scheme, Racket, Clojure
SML, Ocaml, F# , Haskell (full language) , Scala , Smalltalk, Ruby
What is scala?

Scala is a statically typed JVM language that has
transparent interoperability with Java.
Both object oriented and functional language
Why Scala?

Lightweight syntax
Combines functional and object-oriented approaches
Advanced type system: everything has a type
Strong type inference
Performance comparable to Java
Fully interoperable with Java
Example of Scala High-level syntax

Scala form
class person(val name: String , val age: Int) { ...}
Java form
class person
{
private String name;
private int age;
Peron(String name, int age)
{
this.name = name;
this.age = age;
}
}
continue
val list = List(2,5,4)
val newList = (list map(x => x*x)) sortWith(_ > _)
//newList = list(4,16,25)
Java form ???
val people: Array[Person]
val (minors,adults) = people partition (_.age < 18)
Java form ???
Subsitution Model

The idea underlying this model is that all evaluation
does is reduce an expression to a value.
It can be applied to all expressions, as long as they
have no side effects.
Lambda calculus
Non-primitive expression
A non-primitive expression is evaluated as follows:
1. Take the leftmost operator
2. Evaluate its operands (left before right)
3. Apply the operator to the operands
(2 * pi) * radius
(2 * 3.14159) * radius
6.28318 * radius
6.28318 * 10
62.8318
Parameterized functions substitution

1. Evaluate all function arguments, from left to right
2. Replace the function application by the function’s
right-hand side, and, at the same time
3. Replace the formal parameters of the function by
the actual arguments
Example

1.
2.
3.
4.
5.
6.
7.
8.

sumOfSquares(3, 2+2)
sumOfSquares(3, 4)
square(3) + square(4)
3 * 3 + square(4)
9 + square(4)
9+4*4
9 + 16
25
Scala Substitution model

What if right hand side does not terminate ?
two elements for storing expressions in Scala: def and val
def loop: Boolean = loop
def x = loop //it is ok
val x = loop // it will lead to an infinite loop.
As you see the difference between val and def becomes apparent when
the right hand side does not terminate. Val is changed to its value when it
is defined but the value of def is substituted where it is used.
val & def continue

def:
1. can have parameters
def cube(x: Int): Int = x*x*x
2. Call-by-name
val:
1. The value of it is substituted as it is defined. In other
words: call-by-value
Call-by-name function parameters

sumOfSquares(x: Int , y: => Int)
sumOfSquares(3, 2+2)
square(3) + square(2+2)
3 * 3 + square(2+2)
9 + square(2+2)
9 + (2+2) * (2+2)
9 + 4 * (2+2)
9+4*4
25
Higher-Order functions
Functions are expressions so they can be:
Defined anywhere included in other functions
sent to other functions as parameters
Returned from other functions
def fact(x: Int) = if(x ==0) 1 else x*fact(x-1)
def cube(x: Int) = x*x
def processOnSums( f: Int => Int , a: Int , b: Int) = f(a) + f(b)
processOnSums(cube, 2 , 3 ) // Output = 2*2 + 3*3
anonymous function: x=> x*x
processOnSums(fact , 2 , 3 ) // Output: 2*1 + 3*2*1
Currying
def sum(f: Int => Int, a: Int, b: Int): Int = if (a > b) 0
else f(a) + sum(f, a + 1, b)
def sumInts(a: Int, b: Int) = sum(x=>x, a, b)
def sumCubes(a: Int, b: Int) = sum(x=> x*x, a, b)
def sumFactorials(a: Int, b: Int) = sum(x=>fact(x), a, b)
Can we make it even shorter???
continue
def sum(f: Int => Int): (Int, Int) => Int = {
def sumF(a: Int, b: Int): Int =
if (a > b) 0
else f(a) + sumF(a + 1, b)
sumF
}
Sum returns another function
We can define like this:
def sumInts = sum(x => x)
def sumCubes = sum(x => x * x * x)
def sumFactorials = sum(fact)
sumCubes(1, 10) + sumFactorials(10, 20)
Even shorter???
continue
The answer is yes.
sum (cube) (1, 10)
Write once, program many times. ..
Classes
Two kinds of instant field initialization:
Class myClass(input1: Int, input2: Int)
{
Val a = input1
Vab b = input2
}
class myClass(val input1: Int, val input2: Int){…}
Auxiliary Constructors
In order to create auxiliary constructors, define
method this with required parameters.
Class myClass(input1: Int, input2: Int)
{
def this(input1: Int) = this (input1, 0)
}
Inheritance

Inheritance rules so similar to java
Traits are alternative for interfaces
Why do we need a new structure ?
In java classes can have only one super class, but what if
a class need to inherit from several supertypes ???
This is why scala introduces traits.
Trait
trait super
{
val a = 5
def b = a*2
def c(x: Int) = a*x
}
class sub extends Object with super{…}
Class Hierarchies
Imports
Int  scala.Int
Boolean  scala.Boolean
Object  java.lang.Object
require  scala.Predef.require
assert  scala.Predef.assert
Object Definition
The same as java. with new notation
Val myList = new List(1,2,3)
The other form:
Val myList = List(1,2,3)
What happened? Whre is new? We will see…
Singletone Objects

What is singleton object and why do we need it?
The reason we used singleton classes was to create
just one object of a certain type.
Scala gives us a powerful tool called singleton object
that ease the procedure we used to do with singleton
classes in java.
Example

object myObject
{
def +(x: java.lang.String) = x + " and "
}
def names = myObject + "Ehsan" + "Sana"
println(names)
//output Ehsan and Sana
Apply Method

Still don’t know how compiler translates this:
Val myList = List(1,2,3)
We can create a new object just as we call a function with
implenting apply method.
Reason: We are just trying to show the use of apply method as a
handy way of closing the gap between functions and objects in
Scala.
Implementation of Apply Method for
List
object List extends List
{
def apply[A](xs: A*): List[A]
//Creates a list with the specified elements.
}
Immutable Collections

Lists
Maps
a fundamental structure in many functional languages
is the immutable linked list.
List Implementation

List(List(1, 2)),List(3)
continue

1.
2.
3.
4.

val city= List(“Mashhad”,”Tehran”,”Abadan)
val city = “Mashhad”::”Tehran”::”Abadan::Nil
val city = “Mashhad”::(”Tehran”::(“Abadan”::Nil)))
val city = Nil.::(“Abadan).::(“Tehran”).::(“Mashhad)”
Example

def sum(xs: List[Int]): Int = if (xs.isEmpty) 0
else xs.head + sum(xs.tail)
Sums the elements of the list
Immutable Maps

val map = Map("Tehran" -> "Iran" , "Paris" -> "France")
println(map.keys) // output: Set(Tehran, Paris)
Does the String class has a method ->? The answer is no.
We will see how this is translated…
Partial Functions

partial functions obey pattern matching rules and syntax.
Instead of switch case structure here we have match and case
wide range of usage in collections and actors
Partial function is a trait
and its Constructor takes two types; Input type and output type.
It has two abstract values too; apply(v1 a: A): B and isDefinedAt(x : A):
Boolean
Example

val p = new PartialFunction[Int, Any] {
def apply(xs: Int) = xs match {
case xs => 1/xs.doubleValue()
case _ => 1/xs
}
def isDefinedAt(xs: Int) = xs match {
case 0 => false
case _ => true
}
}
println(p(2)) //output: 0.5
println(p(0))// output: Infinity No exception is thrown
Threads

Threads in java: shared objects and lock model
Synchronized and concurrency library

always control threads to not to let them have access
on a shared object at a time, using blocks
Result: race conditions, deadlocks and nondeterminism.
Actors

Scala suggest shared-nothing, message-passing model.
object firstActor extends Actor {
def act() {
for (i <- 1 to 3) {
println("act" + i)
Thread.sleep(1000)
}
}
firstActor.start() //output: act1 act2 act3
Problem

If actors do not have shared objects how do they
connect each other???
So simple: sending message…
Receive Method

val echoActor = actor {
while (true)
Partial function
{
receive { case msg => println("received message: "+ msg) }
}
}
console: echoActor ! “hi”
output: hi
How receive works?

Does not stay on a receive line.
Messages goes to inbox waiting for actor to call
receive.
receive invoke IsDefinedAt method to make sure the
input is valid.
If input is valid, receive sends the it’s body to apply
method otherwise it throw an exception.
Example

val reciever = actor {
receive {
case x: Int => // Only Int is valid as input
println("Got an Int: "+ x)
}
}
reciever ! “hello world” //output: Nothing
receiver ! 4 // output: Got an Int: 4
Disadvantage

Low performance implementation of imperative
structures compared to java.

Weitere ähnliche Inhalte

Was ist angesagt?

Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and typesDaman Toor
 
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 Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in javaMahmoud Ali
 
Java Tutorial Lab 8
Java Tutorial Lab 8Java Tutorial Lab 8
Java Tutorial Lab 8Berk Soysal
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and ClassesSvetlin Nakov
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java DevelopersMartin Ockajak
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for HaskellMartin Ockajak
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 

Was ist angesagt? (20)

Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Scala functions
Scala functionsScala functions
Scala functions
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
Java Tutorial Lab 8
Java Tutorial Lab 8Java Tutorial Lab 8
Java Tutorial Lab 8
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
Class method
Class methodClass method
Class method
 
Cats in Scala
Cats in ScalaCats in Scala
Cats in Scala
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 

Andere mochten auch

MCA-I-COA- overview of register transfer, micro operations and basic computer...
MCA-I-COA- overview of register transfer, micro operations and basic computer...MCA-I-COA- overview of register transfer, micro operations and basic computer...
MCA-I-COA- overview of register transfer, micro operations and basic computer...Rai University
 
Moore's Law Statistical Validation [Updated] - Sanjoy Sanyal
Moore's Law Statistical Validation [Updated] - Sanjoy SanyalMoore's Law Statistical Validation [Updated] - Sanjoy Sanyal
Moore's Law Statistical Validation [Updated] - Sanjoy SanyalSanjoy Sanyal
 
Basic computer organization
Basic computer organizationBasic computer organization
Basic computer organizationNitesh Singh
 
Chapter02 basic computer organization
Chapter02   basic computer organizationChapter02   basic computer organization
Chapter02 basic computer organizationAinuddin Yousufzai
 
Computer organiztion5
Computer organiztion5Computer organiztion5
Computer organiztion5Umang Gupta
 
Basic Computer Organization and Design
Basic Computer Organization and DesignBasic Computer Organization and Design
Basic Computer Organization and DesignKamal Acharya
 
Basic Computer Organization and Design
Basic Computer Organization and DesignBasic Computer Organization and Design
Basic Computer Organization and Designmekind
 

Andere mochten auch (15)

MCA-I-COA- overview of register transfer, micro operations and basic computer...
MCA-I-COA- overview of register transfer, micro operations and basic computer...MCA-I-COA- overview of register transfer, micro operations and basic computer...
MCA-I-COA- overview of register transfer, micro operations and basic computer...
 
Moore's Law Statistical Validation [Updated] - Sanjoy Sanyal
Moore's Law Statistical Validation [Updated] - Sanjoy SanyalMoore's Law Statistical Validation [Updated] - Sanjoy Sanyal
Moore's Law Statistical Validation [Updated] - Sanjoy Sanyal
 
Basic computer organization
Basic computer organizationBasic computer organization
Basic computer organization
 
50 years of Moore's Law.
50 years of Moore's Law.50 years of Moore's Law.
50 years of Moore's Law.
 
Lecture1 ch01
Lecture1 ch01Lecture1 ch01
Lecture1 ch01
 
Lecture 16
Lecture 16Lecture 16
Lecture 16
 
Lecture 11
Lecture 11Lecture 11
Lecture 11
 
Ch01
Ch01Ch01
Ch01
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Processors
ProcessorsProcessors
Processors
 
Processor powerpoint 2
Processor powerpoint 2Processor powerpoint 2
Processor powerpoint 2
 
Chapter02 basic computer organization
Chapter02   basic computer organizationChapter02   basic computer organization
Chapter02 basic computer organization
 
Computer organiztion5
Computer organiztion5Computer organiztion5
Computer organiztion5
 
Basic Computer Organization and Design
Basic Computer Organization and DesignBasic Computer Organization and Design
Basic Computer Organization and Design
 
Basic Computer Organization and Design
Basic Computer Organization and DesignBasic Computer Organization and Design
Basic Computer Organization and Design
 

Ähnlich wie Principles of functional progrmming in scala

Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in ScalaKnoldus Inc.
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closuresKnoldus Inc.
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture ThreeAngelo Corsaro
 

Ähnlich wie Principles of functional progrmming in scala (20)

Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closures
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
scala.ppt
scala.pptscala.ppt
scala.ppt
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 

Kürzlich hochgeladen

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 

Kürzlich hochgeladen (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 

Principles of functional progrmming in scala

  • 1. Principles of Functional Progrmming in Scala • Moor’s Law • Clock frequency has not raised. • More Complex programs. • Growing in data
  • 3. Example var x = 0 async{ x = x+1 } async{ x = x*2 } // the answer could be 0, 1 or 2 Non-determinism = parallel processing+ mutable values
  • 4. Paradigm In science, a paradigm describes distinct concepts or thought patterns in some scientific discipline. Main programming paradigms: imperative programming functional programming logic programming
  • 5. Imparative paradigm modifying mutable variables, using assignments and control structures such as if-thenelse, loops, break, continue, return.
  • 6. Fucntional Paradigm Immutable states Functions without side-effects Everything is function Functions are expressions not statements
  • 7. Referential transparency once a variable is given a value it never changes. no side effects are possible. Functions are building blocks  functions are free side-effect function call does not affect other functions and it just computes its own output for a specific input sin (pi) = 0 Functions are expressions not statements
  • 8. FP is inspired by mathematics Neither theories nor functions have mutable values. You can combine functions to make more complex functions The result of a function or a theory does not change for different input. (a+b)^2 = a^2 + b^2 + 2*a*b This state doesn’t change for different inputs.
  • 9. Functional Languages Pure(restricted) Functional languages ( no imperative structure) like: Pure Lisp, XSLT, XPath, XQuery, FP,Haskell (without I/O Monad or UnsafePerformIO) Wider sense : Lisp, Scheme, Racket, Clojure SML, Ocaml, F# , Haskell (full language) , Scala , Smalltalk, Ruby
  • 10. What is scala? Scala is a statically typed JVM language that has transparent interoperability with Java. Both object oriented and functional language
  • 11. Why Scala? Lightweight syntax Combines functional and object-oriented approaches Advanced type system: everything has a type Strong type inference Performance comparable to Java Fully interoperable with Java
  • 12. Example of Scala High-level syntax Scala form class person(val name: String , val age: Int) { ...} Java form class person { private String name; private int age; Peron(String name, int age) { this.name = name; this.age = age; } }
  • 13. continue val list = List(2,5,4) val newList = (list map(x => x*x)) sortWith(_ > _) //newList = list(4,16,25) Java form ??? val people: Array[Person] val (minors,adults) = people partition (_.age < 18) Java form ???
  • 14. Subsitution Model The idea underlying this model is that all evaluation does is reduce an expression to a value. It can be applied to all expressions, as long as they have no side effects. Lambda calculus
  • 15. Non-primitive expression A non-primitive expression is evaluated as follows: 1. Take the leftmost operator 2. Evaluate its operands (left before right) 3. Apply the operator to the operands (2 * pi) * radius (2 * 3.14159) * radius 6.28318 * radius 6.28318 * 10 62.8318
  • 16. Parameterized functions substitution 1. Evaluate all function arguments, from left to right 2. Replace the function application by the function’s right-hand side, and, at the same time 3. Replace the formal parameters of the function by the actual arguments
  • 17. Example 1. 2. 3. 4. 5. 6. 7. 8. sumOfSquares(3, 2+2) sumOfSquares(3, 4) square(3) + square(4) 3 * 3 + square(4) 9 + square(4) 9+4*4 9 + 16 25
  • 18. Scala Substitution model What if right hand side does not terminate ? two elements for storing expressions in Scala: def and val def loop: Boolean = loop def x = loop //it is ok val x = loop // it will lead to an infinite loop. As you see the difference between val and def becomes apparent when the right hand side does not terminate. Val is changed to its value when it is defined but the value of def is substituted where it is used.
  • 19. val & def continue def: 1. can have parameters def cube(x: Int): Int = x*x*x 2. Call-by-name val: 1. The value of it is substituted as it is defined. In other words: call-by-value
  • 20. Call-by-name function parameters sumOfSquares(x: Int , y: => Int) sumOfSquares(3, 2+2) square(3) + square(2+2) 3 * 3 + square(2+2) 9 + square(2+2) 9 + (2+2) * (2+2) 9 + 4 * (2+2) 9+4*4 25
  • 21. Higher-Order functions Functions are expressions so they can be: Defined anywhere included in other functions sent to other functions as parameters Returned from other functions def fact(x: Int) = if(x ==0) 1 else x*fact(x-1) def cube(x: Int) = x*x def processOnSums( f: Int => Int , a: Int , b: Int) = f(a) + f(b) processOnSums(cube, 2 , 3 ) // Output = 2*2 + 3*3 anonymous function: x=> x*x processOnSums(fact , 2 , 3 ) // Output: 2*1 + 3*2*1
  • 22. Currying def sum(f: Int => Int, a: Int, b: Int): Int = if (a > b) 0 else f(a) + sum(f, a + 1, b) def sumInts(a: Int, b: Int) = sum(x=>x, a, b) def sumCubes(a: Int, b: Int) = sum(x=> x*x, a, b) def sumFactorials(a: Int, b: Int) = sum(x=>fact(x), a, b) Can we make it even shorter???
  • 23. continue def sum(f: Int => Int): (Int, Int) => Int = { def sumF(a: Int, b: Int): Int = if (a > b) 0 else f(a) + sumF(a + 1, b) sumF } Sum returns another function We can define like this: def sumInts = sum(x => x) def sumCubes = sum(x => x * x * x) def sumFactorials = sum(fact) sumCubes(1, 10) + sumFactorials(10, 20) Even shorter???
  • 24. continue The answer is yes. sum (cube) (1, 10) Write once, program many times. ..
  • 25. Classes Two kinds of instant field initialization: Class myClass(input1: Int, input2: Int) { Val a = input1 Vab b = input2 } class myClass(val input1: Int, val input2: Int){…}
  • 26. Auxiliary Constructors In order to create auxiliary constructors, define method this with required parameters. Class myClass(input1: Int, input2: Int) { def this(input1: Int) = this (input1, 0) }
  • 27. Inheritance Inheritance rules so similar to java Traits are alternative for interfaces Why do we need a new structure ? In java classes can have only one super class, but what if a class need to inherit from several supertypes ??? This is why scala introduces traits.
  • 28. Trait trait super { val a = 5 def b = a*2 def c(x: Int) = a*x } class sub extends Object with super{…}
  • 30. Imports Int  scala.Int Boolean  scala.Boolean Object  java.lang.Object require  scala.Predef.require assert  scala.Predef.assert
  • 31. Object Definition The same as java. with new notation Val myList = new List(1,2,3) The other form: Val myList = List(1,2,3) What happened? Whre is new? We will see…
  • 32. Singletone Objects What is singleton object and why do we need it? The reason we used singleton classes was to create just one object of a certain type. Scala gives us a powerful tool called singleton object that ease the procedure we used to do with singleton classes in java.
  • 33. Example object myObject { def +(x: java.lang.String) = x + " and " } def names = myObject + "Ehsan" + "Sana" println(names) //output Ehsan and Sana
  • 34. Apply Method Still don’t know how compiler translates this: Val myList = List(1,2,3) We can create a new object just as we call a function with implenting apply method. Reason: We are just trying to show the use of apply method as a handy way of closing the gap between functions and objects in Scala.
  • 35. Implementation of Apply Method for List object List extends List { def apply[A](xs: A*): List[A] //Creates a list with the specified elements. }
  • 36. Immutable Collections Lists Maps a fundamental structure in many functional languages is the immutable linked list.
  • 38. continue 1. 2. 3. 4. val city= List(“Mashhad”,”Tehran”,”Abadan) val city = “Mashhad”::”Tehran”::”Abadan::Nil val city = “Mashhad”::(”Tehran”::(“Abadan”::Nil))) val city = Nil.::(“Abadan).::(“Tehran”).::(“Mashhad)”
  • 39. Example def sum(xs: List[Int]): Int = if (xs.isEmpty) 0 else xs.head + sum(xs.tail) Sums the elements of the list
  • 40. Immutable Maps val map = Map("Tehran" -> "Iran" , "Paris" -> "France") println(map.keys) // output: Set(Tehran, Paris) Does the String class has a method ->? The answer is no. We will see how this is translated…
  • 41. Partial Functions partial functions obey pattern matching rules and syntax. Instead of switch case structure here we have match and case wide range of usage in collections and actors Partial function is a trait and its Constructor takes two types; Input type and output type. It has two abstract values too; apply(v1 a: A): B and isDefinedAt(x : A): Boolean
  • 42. Example val p = new PartialFunction[Int, Any] { def apply(xs: Int) = xs match { case xs => 1/xs.doubleValue() case _ => 1/xs } def isDefinedAt(xs: Int) = xs match { case 0 => false case _ => true } } println(p(2)) //output: 0.5 println(p(0))// output: Infinity No exception is thrown
  • 43. Threads Threads in java: shared objects and lock model Synchronized and concurrency library always control threads to not to let them have access on a shared object at a time, using blocks Result: race conditions, deadlocks and nondeterminism.
  • 44. Actors Scala suggest shared-nothing, message-passing model. object firstActor extends Actor { def act() { for (i <- 1 to 3) { println("act" + i) Thread.sleep(1000) } } firstActor.start() //output: act1 act2 act3
  • 45. Problem If actors do not have shared objects how do they connect each other??? So simple: sending message…
  • 46. Receive Method val echoActor = actor { while (true) Partial function { receive { case msg => println("received message: "+ msg) } } } console: echoActor ! “hi” output: hi
  • 47. How receive works? Does not stay on a receive line. Messages goes to inbox waiting for actor to call receive. receive invoke IsDefinedAt method to make sure the input is valid. If input is valid, receive sends the it’s body to apply method otherwise it throw an exception.
  • 48. Example val reciever = actor { receive { case x: Int => // Only Int is valid as input println("Got an Int: "+ x) } } reciever ! “hello world” //output: Nothing receiver ! 4 // output: Got an Int: 4
  • 49. Disadvantage Low performance implementation of imperative structures compared to java.