SlideShare a Scribd company logo
Functional Programming with Scala




Neelkanth Sachdeva
Consultant
Knoldus Software LLP
neelkanthsachdeva.wordpress.com
Programming Languages

  One approach to the software crisis is to introduce new
  programming languages that supports following :
→Reusability
→ Clear , Concise and High performance code.
→ Rapid prototyping
→ Reduces time and cost for development
Why Scala ?
Scala programming language

Born from the mind of Martin Odersky.
A good mix of :
  → Object orientation
  → functional programming
  → A powerful type system code
  → Eligent and powerful code then other
    languages
Scala features :
Scala attempts to blend three dichotomies of
 thought into one language. These are:

→ Functional programming and object-oriented
   programming
→ Expressive syntax and static typing
→ Advanced language features and rich Java
  integration
 Let us understand these one-by-one :-
Functional programming and object
           oriented programming
→ Functional programming is style of programming in which the basic
 method of computation is the application of functions to arguments.
→ Functional programming puts special emphasis on the “verbs” of a
 program & Object-oriented programming puts special emphasis on
 “nouns” and attaches verbs to them.
→ The two approaches are almost inverses of each other, with one
 being “top down” and the other “bottom up.”
→ Functional programming approaches software as the combination
 and application of functions.
→ It tends to decompose software into behaviors, or actions that need
 to be performed, usually in a bottom-up fashion.
Didn't understood...Have a look ?

Scenerio : “A Lion catches a deer and eats it.”

 The OOPS approach :

    class Deer
    class Lion {
         def catch(d: Deer): Unit = ...
         def eat(): Unit = ...
     }
   val lion = new Lion
   val deer = new Deer
   lion.catch(deer)
  lion.eat()
Functional programming approach

trait Lion
trait Deer
trait Catch
trait FullTummy


def catch(hunter: Lion, prey: deer): Lion with Catch
def eat(consumer: Lion with Catch): Lion with FullTummy
val story = (catch _) andThen (eat _)
story(new Lion, new Deer)
Static typing and expressiveness

The Scala type system allows expressive code.
 Scala made a few simple design decisions that help
 make it expressive:
- Changing sides of type annotation
- Type inference
- Scalable syntax
- User-defined implicits
Transparently working with the JVM

→ Seamless integration with Java and the JVM
→ Using Java libraries from Scala is seamless
  because Java idioms map directly into Scala
  idioms.
→ libraries written in Java can be imported into
 Scala as is.
Recursion

Recursion plays a larger role in pure functional
programming than in imperative programming, in part
because of the restriction that variables are immutable.
For example, you can’t have loop counters, which would
change on each pass through a loop. One way to
implement looping in a purely functional way is with
recursion.
Lets have a look :
Calculating factorials provides a good example. Here is an
imperative loop implementation.
Imperative loop implementation

def factorialWithLoop(i: BigInt): BigInt = {
     var resultantValue = BigInt(1)
     for (h <- 2 to i.intValue)
      resultantValue *= h
     resultantValue
 }


for (i <- 1 to 10)
println("factorial of " + i + " is " + factorialWithLoop(i))
Functional Approach

def factorial_Functional(i: BigInt): BigInt = i match {
     case _ if i == 1 => i
     case _ => i * factorial_Functional(i - 1)
 }


for (i <- 1 to 10)
  println("factorial of " + i + " is " + factorial_Functional(i))
How short and effective it is ..... !
Introduction to implicits

Scala provides an implicit keyword that can be used in two ways:
→ method or variable definitions
→ method parameter lists


scala> def findAnInt(implicit x : Int) = x
findAnInt: (implicit x: Int)Int


scala> findAnInt
<console>:7: error: could not find implicit value for parameter x: Int
findAnInt
^
The findAnInt method is called without specifying any
  argument list. The compiler complains that it can’t find an
  implicit value for the x parameter. We’ll provide one, as
  follows:



scala> implicit val test = 5
test: Int = 5


scala> findAnInt
res3: Int = 5
Avoid call site evaluation ?
Sometimes we want arguments not be evaluated at
 call site :
def executeMe(msgString: () => String) {
println(msgString())
}
Now calling the method like :
executeMe(() => "This" + " is" + " not"+ " looking" + "
  good!")


Not looking good...isn’t it?
How we can do this in a good way :
We can use => in a type annotation to define a by-name
 parameter.

// by-name parameter
 def iAmOk(msgString: => String) { println(msgString) }


Now calling it as :
/*
 * Using by-name Parameter
 */
 iAmOk("This" + " is" + " an" + " use"+" case"+ " by-name" + " param.")
Partial Functions :

→ Need not be defined on its whole domain

→ PartialFunction is a subtype of Function1:
   trait PartialFunction [-A, +B] extends A => B


→ Use isDefinedAt to determine whether a partial
 function is defined for a given value
 or not.
Using isDefinedAt :
object KnolXPartialFunction {
    // defined a map
    val KnolXMap = Map(1 -> "Neelkanth", 2 -> "Sachdeva")
    def main(args: Array[String]) {
        val booleanAnswer1 = KnolXMap.isDefinedAt(1)
        println("The Answer is " + booleanAnswer1)
        val booleanAnswer2 = KnolXMap.isDefinedAt(3)
        println("The Answer is " + booleanAnswer2)
    }
}
Output should be as :
The Answer is true
The Answer is false
Use a block of case alternatives to define a
  partial function literal :

scala> (’a’ to ’f’).zipWithIndex filter {
| case (_, i) => i % 2 == 0
|}

Result should be like this :

res0: ... = Vector((a,0), (c,2), (e,4))
Using the right collection

 The Scala collections library is the single most impressive
 library in the Scala ecosystem. The Scala collections provide
 many ways of storing and manipulating data, which can be
 overwhelming. Because most of the methods defined on Scala
 collections are available on every collection.
 Scala’s collections also split into three dichotomies:
→ Immutableand mutable collections
→ Eager and delayed evaluation
→ Sequential and parallel evaluation
The collection hierarchy

Traversable : The Traversable trait is defined in terms of the
  foreach method.This method is an internal iterator---that is, the
  foreach method takes a function that operates on a single
  element of the collection and applies it to every element of the
  collection. Travers-able collections don’t provide any way to
  stop traversing inside the foreach.
Iterable : The Iterable trait is defined in terms of the iterator
  method. This returns an external iterator that you can use to
  walk through the items in the collection.
scala> val names = Iterable("Josh", "Jim")
names: Iterable[java.lang.String] = List(Josh, Jim)
Seq : The Seq trait is defined in terms of the length
 and apply method. It represents collections that
 have a sequential ordering. We can use the
 apply method to index into the collection by its
 ordering. The length methodreturns the size of
 the collection.
scala> val x = Seq(2,1,30,-2,20,1,2,0)
x: Seq[Int] = List(2, 1, 30, -2, 20, 1, 2, 0)
scala> x.tails map (_.take(2)) filter (_.length > 1)
  map (_.sum) toList
res0: List[Int] = List(3, 31, 28, 18, 21, 3, 2)
LinearSeq: The LinearSeq trait is used to denote that a
  collection can be split into a head and tail component.
IndexedSeq: The IndexedSeq trait is similar to the Seq trait
  except that it implies that random access of collection
  elements is efficient that is, accessing elements of a
  collectionshould be constant or near constant.
scala> val x = IndexedSeq(1, 2, 3)
x: IndexedSeq[Int] = Vector(1, 2, 3)
scala> x.updated(1, 5)
res0: IndexedSeq[Int] = Vector(1, 5, 3)


Set
Map
Some special & powerful collection methods:


→ sliding : Groups elements in fixed size blocks by passing a
  ”sliding window” over them .


→ Curried methods : A method can have more than one
 parameter list, which is called currying2 .



→ foldLeft : foldLeft transforms a collection into a single value.
Using sliding method :
object KnolXSliding {
def KnolXSlide = {
        1 to 6 sliding 4 foreach println
    }
    def main(args: Array[String]) {
        // Call the sliding method
        KnolXSlide
        }
}
Output should be :
Vector(1, 2, 3, 4)
Vector(2, 3, 4, 5)
Vector(3, 4, 5, 6)
Using Curried methods :

object KnolXCurried {
    // Passing more then one parameters
    def KnolXadd(a: Int)(b: Int)(c: String) =
println("The Tota Sum is "+ (a + b) + " " + c)
    def main(args: Array[String]) {
        KnolXadd(2)(9)("Wowwwwwww !")
    }
}
Output should be :
The Total Sum is 11 Wowwwwwww !
Using foldLeft method :

object KnolXfoldLeft {
    def main(args: Array[String]) {
        val addAll = Seq(1, 2, 3).foldLeft(0)(_ + _)
        println("Sum is"+addAll)
    }
}
Output should be :
Sum is 6
Let us have a feel of some XML as well

          Introduction to


       Working with XML
Semi-structured data

→ XML is a form of semi-structured data.
→ It is more structured than plain strings, because it
 organizes the contents of the data into a tree
→ Semi-structured data is very helpful any time you need to
 serialize program data for saving in a file or shipping
 across a network.
→ XML is the most widely used on the Internet. There are
 XML tools on most operating systems, and most
 programming languages have XML libraries available
XML overview

// Illegal XML
One <pod>, two <pod>, three <pod> zoo
// Also illegal
<pod>Three <peas> in the </pod></peas>


//Ok
<pod>Three <peas></peas> in the </pod>
Scala lets you type in XML as a literal anywhere that an expression is valid :


scala> <a>
This is some XML.
Here is a tag: <atag/>
</a>
res0: scala.xml.Elem =
<a>
This is some XML.
Here is a tag: <atag></atag>
</a>


scala> <a> {"hello"+", world"} </a>
res1: scala.xml.Elem = <a> hello, world </a>
Can we Try Something ?

scala> val yearMade = 1955
yearMade: Int = 1955
scala>
<a> { if (yearMade < 2000) <old>{yearMade}</old>
else xml.NodeSeq.Empty }
</a>
res2: scala.xml.Elem =
<a> <old>1955</old>
</a>
Thank You

More Related Content

What's hot (20)

Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Hyderabad Scalability Meetup
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming Language
Himanshu Choudhary
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Java8
Java8Java8
Java8
Felipe Mamud
 
Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
Andrzej Grzesik
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Scala test
Scala testScala test
Scala test
Inphina Technologies
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
Khurshid Asghar
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
Mumbai Academisc
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
Manav Prasad
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
Angelo Corsaro
 

Similar to Functional programming with Scala (20)

The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
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 Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Andrew Phillips
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
Alf Kristian Støyle
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
Muhammad Fayyaz
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
Neelkanth Sachdeva
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
Knoldus Inc.
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
Wojciech Pituła
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
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 Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Andrew Phillips
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
Knoldus Inc.
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
Ad

Recently uploaded (20)

Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
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
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
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
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
IntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdfIntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdf
Luiz Carneiro
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
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
 
Trends Report: Artificial Intelligence (AI)
Trends Report: Artificial Intelligence (AI)Trends Report: Artificial Intelligence (AI)
Trends Report: Artificial Intelligence (AI)
Brian Ahier
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
“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
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
Extend-Microsoft365-with-Copilot-agents.pptx
Extend-Microsoft365-with-Copilot-agents.pptxExtend-Microsoft365-with-Copilot-agents.pptx
Extend-Microsoft365-with-Copilot-agents.pptx
hoang971
 
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
 
AI Creative Generates You Passive Income Like Never Before
AI Creative Generates You Passive Income Like Never BeforeAI Creative Generates You Passive Income Like Never Before
AI Creative Generates You Passive Income Like Never Before
SivaRajan47
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
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
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
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
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
IntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdfIntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdf
Luiz Carneiro
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
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
 
Trends Report: Artificial Intelligence (AI)
Trends Report: Artificial Intelligence (AI)Trends Report: Artificial Intelligence (AI)
Trends Report: Artificial Intelligence (AI)
Brian Ahier
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
“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
 
Extend-Microsoft365-with-Copilot-agents.pptx
Extend-Microsoft365-with-Copilot-agents.pptxExtend-Microsoft365-with-Copilot-agents.pptx
Extend-Microsoft365-with-Copilot-agents.pptx
hoang971
 
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
 
AI Creative Generates You Passive Income Like Never Before
AI Creative Generates You Passive Income Like Never BeforeAI Creative Generates You Passive Income Like Never Before
AI Creative Generates You Passive Income Like Never Before
SivaRajan47
 
Ad

Functional programming with Scala

  • 1. Functional Programming with Scala Neelkanth Sachdeva Consultant Knoldus Software LLP neelkanthsachdeva.wordpress.com
  • 2. Programming Languages One approach to the software crisis is to introduce new programming languages that supports following : →Reusability → Clear , Concise and High performance code. → Rapid prototyping → Reduces time and cost for development
  • 4. Scala programming language Born from the mind of Martin Odersky. A good mix of : → Object orientation → functional programming → A powerful type system code → Eligent and powerful code then other languages
  • 6. Scala attempts to blend three dichotomies of thought into one language. These are: → Functional programming and object-oriented programming → Expressive syntax and static typing → Advanced language features and rich Java integration Let us understand these one-by-one :-
  • 7. Functional programming and object oriented programming → Functional programming is style of programming in which the basic method of computation is the application of functions to arguments. → Functional programming puts special emphasis on the “verbs” of a program & Object-oriented programming puts special emphasis on “nouns” and attaches verbs to them. → The two approaches are almost inverses of each other, with one being “top down” and the other “bottom up.” → Functional programming approaches software as the combination and application of functions. → It tends to decompose software into behaviors, or actions that need to be performed, usually in a bottom-up fashion.
  • 8. Didn't understood...Have a look ? Scenerio : “A Lion catches a deer and eats it.” The OOPS approach : class Deer class Lion { def catch(d: Deer): Unit = ... def eat(): Unit = ... } val lion = new Lion val deer = new Deer lion.catch(deer) lion.eat()
  • 9. Functional programming approach trait Lion trait Deer trait Catch trait FullTummy def catch(hunter: Lion, prey: deer): Lion with Catch def eat(consumer: Lion with Catch): Lion with FullTummy val story = (catch _) andThen (eat _) story(new Lion, new Deer)
  • 10. Static typing and expressiveness The Scala type system allows expressive code. Scala made a few simple design decisions that help make it expressive: - Changing sides of type annotation - Type inference - Scalable syntax - User-defined implicits
  • 11. Transparently working with the JVM → Seamless integration with Java and the JVM → Using Java libraries from Scala is seamless because Java idioms map directly into Scala idioms. → libraries written in Java can be imported into Scala as is.
  • 12. Recursion Recursion plays a larger role in pure functional programming than in imperative programming, in part because of the restriction that variables are immutable. For example, you can’t have loop counters, which would change on each pass through a loop. One way to implement looping in a purely functional way is with recursion. Lets have a look : Calculating factorials provides a good example. Here is an imperative loop implementation.
  • 13. Imperative loop implementation def factorialWithLoop(i: BigInt): BigInt = { var resultantValue = BigInt(1) for (h <- 2 to i.intValue) resultantValue *= h resultantValue } for (i <- 1 to 10) println("factorial of " + i + " is " + factorialWithLoop(i))
  • 14. Functional Approach def factorial_Functional(i: BigInt): BigInt = i match { case _ if i == 1 => i case _ => i * factorial_Functional(i - 1) } for (i <- 1 to 10) println("factorial of " + i + " is " + factorial_Functional(i)) How short and effective it is ..... !
  • 15. Introduction to implicits Scala provides an implicit keyword that can be used in two ways: → method or variable definitions → method parameter lists scala> def findAnInt(implicit x : Int) = x findAnInt: (implicit x: Int)Int scala> findAnInt <console>:7: error: could not find implicit value for parameter x: Int findAnInt ^
  • 16. The findAnInt method is called without specifying any argument list. The compiler complains that it can’t find an implicit value for the x parameter. We’ll provide one, as follows: scala> implicit val test = 5 test: Int = 5 scala> findAnInt res3: Int = 5
  • 17. Avoid call site evaluation ? Sometimes we want arguments not be evaluated at call site : def executeMe(msgString: () => String) { println(msgString()) } Now calling the method like : executeMe(() => "This" + " is" + " not"+ " looking" + " good!") Not looking good...isn’t it?
  • 18. How we can do this in a good way : We can use => in a type annotation to define a by-name parameter. // by-name parameter def iAmOk(msgString: => String) { println(msgString) } Now calling it as : /* * Using by-name Parameter */ iAmOk("This" + " is" + " an" + " use"+" case"+ " by-name" + " param.")
  • 19. Partial Functions : → Need not be defined on its whole domain → PartialFunction is a subtype of Function1: trait PartialFunction [-A, +B] extends A => B → Use isDefinedAt to determine whether a partial function is defined for a given value or not.
  • 20. Using isDefinedAt : object KnolXPartialFunction { // defined a map val KnolXMap = Map(1 -> "Neelkanth", 2 -> "Sachdeva") def main(args: Array[String]) { val booleanAnswer1 = KnolXMap.isDefinedAt(1) println("The Answer is " + booleanAnswer1) val booleanAnswer2 = KnolXMap.isDefinedAt(3) println("The Answer is " + booleanAnswer2) } } Output should be as : The Answer is true The Answer is false
  • 21. Use a block of case alternatives to define a partial function literal : scala> (’a’ to ’f’).zipWithIndex filter { | case (_, i) => i % 2 == 0 |} Result should be like this : res0: ... = Vector((a,0), (c,2), (e,4))
  • 22. Using the right collection The Scala collections library is the single most impressive library in the Scala ecosystem. The Scala collections provide many ways of storing and manipulating data, which can be overwhelming. Because most of the methods defined on Scala collections are available on every collection. Scala’s collections also split into three dichotomies: → Immutableand mutable collections → Eager and delayed evaluation → Sequential and parallel evaluation
  • 23. The collection hierarchy Traversable : The Traversable trait is defined in terms of the foreach method.This method is an internal iterator---that is, the foreach method takes a function that operates on a single element of the collection and applies it to every element of the collection. Travers-able collections don’t provide any way to stop traversing inside the foreach. Iterable : The Iterable trait is defined in terms of the iterator method. This returns an external iterator that you can use to walk through the items in the collection. scala> val names = Iterable("Josh", "Jim") names: Iterable[java.lang.String] = List(Josh, Jim)
  • 24. Seq : The Seq trait is defined in terms of the length and apply method. It represents collections that have a sequential ordering. We can use the apply method to index into the collection by its ordering. The length methodreturns the size of the collection. scala> val x = Seq(2,1,30,-2,20,1,2,0) x: Seq[Int] = List(2, 1, 30, -2, 20, 1, 2, 0) scala> x.tails map (_.take(2)) filter (_.length > 1) map (_.sum) toList res0: List[Int] = List(3, 31, 28, 18, 21, 3, 2)
  • 25. LinearSeq: The LinearSeq trait is used to denote that a collection can be split into a head and tail component. IndexedSeq: The IndexedSeq trait is similar to the Seq trait except that it implies that random access of collection elements is efficient that is, accessing elements of a collectionshould be constant or near constant. scala> val x = IndexedSeq(1, 2, 3) x: IndexedSeq[Int] = Vector(1, 2, 3) scala> x.updated(1, 5) res0: IndexedSeq[Int] = Vector(1, 5, 3) Set Map
  • 26. Some special & powerful collection methods: → sliding : Groups elements in fixed size blocks by passing a ”sliding window” over them . → Curried methods : A method can have more than one parameter list, which is called currying2 . → foldLeft : foldLeft transforms a collection into a single value.
  • 27. Using sliding method : object KnolXSliding { def KnolXSlide = { 1 to 6 sliding 4 foreach println } def main(args: Array[String]) { // Call the sliding method KnolXSlide } } Output should be : Vector(1, 2, 3, 4) Vector(2, 3, 4, 5) Vector(3, 4, 5, 6)
  • 28. Using Curried methods : object KnolXCurried { // Passing more then one parameters def KnolXadd(a: Int)(b: Int)(c: String) = println("The Tota Sum is "+ (a + b) + " " + c) def main(args: Array[String]) { KnolXadd(2)(9)("Wowwwwwww !") } } Output should be : The Total Sum is 11 Wowwwwwww !
  • 29. Using foldLeft method : object KnolXfoldLeft { def main(args: Array[String]) { val addAll = Seq(1, 2, 3).foldLeft(0)(_ + _) println("Sum is"+addAll) } } Output should be : Sum is 6
  • 30. Let us have a feel of some XML as well Introduction to Working with XML
  • 31. Semi-structured data → XML is a form of semi-structured data. → It is more structured than plain strings, because it organizes the contents of the data into a tree → Semi-structured data is very helpful any time you need to serialize program data for saving in a file or shipping across a network. → XML is the most widely used on the Internet. There are XML tools on most operating systems, and most programming languages have XML libraries available
  • 32. XML overview // Illegal XML One <pod>, two <pod>, three <pod> zoo // Also illegal <pod>Three <peas> in the </pod></peas> //Ok <pod>Three <peas></peas> in the </pod>
  • 33. Scala lets you type in XML as a literal anywhere that an expression is valid : scala> <a> This is some XML. Here is a tag: <atag/> </a> res0: scala.xml.Elem = <a> This is some XML. Here is a tag: <atag></atag> </a> scala> <a> {"hello"+", world"} </a> res1: scala.xml.Elem = <a> hello, world </a>
  • 34. Can we Try Something ? scala> val yearMade = 1955 yearMade: Int = 1955 scala> <a> { if (yearMade < 2000) <old>{yearMade}</old> else xml.NodeSeq.Empty } </a> res2: scala.xml.Elem = <a> <old>1955</old> </a>