SlideShare a Scribd company logo
Functional Programming with Scala




Neelkanth Sachdeva
Software 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
Thank You

More Related Content

What's hot

Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Philip Schwarz
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
Joseph Smith
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Chris Richardson
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshuSidd Singh
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On RandomnessRanel Padon
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
Adam Mukharil Bachtiar
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3
Philip Schwarz
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
WebF
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
John Cant
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Arrays
ArraysArrays
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei
 

What's hot (20)

Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
 
Arrays
ArraysArrays
Arrays
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 

Viewers also liked

Spark in the Maritime Domain
Spark in the Maritime DomainSpark in the Maritime Domain
Spark in the Maritime Domain
Demi Ben-Ari
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
Knoldus Inc.
 
Scala collection
Scala collectionScala collection
Scala collection
Knoldus Inc.
 
Introduction to Option monad in Scala
Introduction to Option monad in ScalaIntroduction to Option monad in Scala
Introduction to Option monad in Scala
Jan Krag
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
Concurrent and Distributed Applications with Akka, Java and Scala
Concurrent and Distributed Applications with Akka, Java and ScalaConcurrent and Distributed Applications with Akka, Java and Scala
Concurrent and Distributed Applications with Akka, Java and Scala
Fernando Rodriguez
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scalaStratio
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
Shahriar Hyder
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
Damian Jureczko
 

Viewers also liked (10)

Spark in the Maritime Domain
Spark in the Maritime DomainSpark in the Maritime Domain
Spark in the Maritime Domain
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
 
Scala collection
Scala collectionScala collection
Scala collection
 
Introduction to Option monad in Scala
Introduction to Option monad in ScalaIntroduction to Option monad in Scala
Introduction to Option monad in Scala
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
 
Concurrent and Distributed Applications with Akka, Java and Scala
Concurrent and Distributed Applications with Akka, Java and ScalaConcurrent and Distributed Applications with Akka, Java and Scala
Concurrent and Distributed Applications with Akka, Java and Scala
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 

Similar to Functional Programming With Scala

Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
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
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
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 for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
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
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
Albert Bifet
 
Scala Intro
Scala IntroScala Intro
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 

Similar to Functional Programming With Scala (20)

Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
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...
 
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...
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
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
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
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
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 

More from Knoldus Inc.

Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
Knoldus Inc.
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
Knoldus Inc.
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
Knoldus Inc.
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
Knoldus Inc.
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
Knoldus Inc.
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
Knoldus Inc.
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
Knoldus Inc.
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
Knoldus Inc.
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
Knoldus Inc.
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
Knoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Knoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
Knoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
Knoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
Knoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
Knoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
Knoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
Knoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
Knoldus Inc.
 

More from Knoldus Inc. (20)

Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 

Recently uploaded

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 

Recently uploaded (20)

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 

Functional Programming With Scala

  • 1. Functional Programming with Scala Neelkanth Sachdeva Software 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