+ All Categories
Home > Data & Analytics > Functional programming in Scala

Functional programming in Scala

Date post: 21-Feb-2017
Category:
Upload: datamantra
View: 199 times
Download: 0 times
Share this document with a friend
39
Functional programming in Scala https://github.com/ganeshayadiyala/functional-programming-in-scala
Transcript
Page 1: Functional programming in Scala

Functional programming in Scala

https://github.com/ganeshayadiyala/functional-programming-in-scala

Page 2: Functional programming in Scala

● Ganesha Yadiyala

● Big data consultant at

datamantra.io

● Consult in spark and scala

[email protected]

Page 3: Functional programming in Scala

Agenda● Programming paradigms● Functional Programming● Advantages of FP● History of Scala ● Basics of scala● Functional Aspect of Scala

Page 4: Functional programming in Scala

Programming Paradigms

Page 5: Functional programming in Scala

Programming Paradigms● Programming Paradigm is a approach to programming● It will be based on set of principles or theory● Different ways of thinking.● Different types

○ Imperative○ Functional

Page 6: Functional programming in Scala

Imperative ProgrammingImperative programming is a programming paradigm that uses statements that change a program's state.

Example :

● C#● C++● Java

Page 7: Functional programming in Scala

Functional ProgrammingA programming style that models computation as the evaluation of expression.

Example:

● Haskell● Erlang● Lisp● Clojure

Page 8: Functional programming in Scala

Expression vs StatementExpression : evaluated to produce a value without changing state.

Statement : executed to update state.

Example:

Expression -> val isEven = if(x%2 == 0) true else false

Page 9: Functional programming in Scala

Example :

Statement -> boolean isEven = true

if(x%2 == 0)

isEven = true

else

isEven = false

Page 10: Functional programming in Scala

Functional Programming

Page 11: Functional programming in Scala

History of Functional Programming● Mathematical abstraction Lambda Calculus was the foundation

for functional Programming● Lambda calculus was developed in 1930s to be used for

functional definition, functional application and recursion.● It states that any computation can be achieved by sending the

input to some black box, which produces its result.● This black box is lambda functions, and in FP it’s functions.● LISP was the first functional programming language. It was

defined by McCarthy in 1958

Page 12: Functional programming in Scala

Imperative vs Functional ProgrammingCharacteristics Imperative Functional

State changes Important Non-existent

Order of execution Important Low importance

Primary flow control Loops, conditions and method (function) calls Function calls

Primary manipulation unit Instances of structures or classes Functions

Page 13: Functional programming in Scala

Characteristics of FP● Immutable data● Lazy evaluation● No side effects● Referential transparency● Functions are first class citizens

Page 14: Functional programming in Scala

Immutable dataMutable Immutable

var collection = [1,2,3,4]

for ( i = 0; i<collection.length; i++) { collection[i]+=1;

}

Uses loop for updating

collection is updated in place

val collection = [1,2,3,4]

val newCollection = collection.map(value => value +1)

Uses transformation for change

Creates a new copy of collection. Leaves

collection intact

Page 15: Functional programming in Scala

Advantages of FP● Better modularity● Shorter code● Increased developer productivity● Less number of bugs● Perfect for distributed computing because of immutability● Easier debugging

Page 16: Functional programming in Scala

Limitations of FP● Real world programs have to do side effects● Difficult to understand for the beginner● Very difficult to debug the nature of lazy evaluation● Memory intensive

Page 17: Functional programming in Scala

History of Scala

Page 18: Functional programming in Scala

Scala History● Martin Odersky is the creator● Curious about compilers from beginning● Created first compiler in 1995 - Pizza

○ Generics,Function pointers, Case class and pattern matching● Led to javac compiler and generics eventually

○ Java is a strict language and hard to implement these new ideas

Page 19: Functional programming in Scala

Scala History cont.. ● 1999 - Started working on a language

○ Combines Object orientation with functional programming○ Created Funnel language○ It was not a user friendly language○ New languages with less libraries are hard to adopt

● In 2001, design for Scala started, released first in 2003● Scala is not an extension of Java● Scala translates into JAVA byte code● One implementation of .Net compatible version, now out dated

Page 20: Functional programming in Scala

Scala Philosophy● Growable language

○ Embed new DSL/add new types● Scalable language

○ Same concepts in small and large applications● Deep rather than broad

○ Focus on abstraction and composition

Page 21: Functional programming in Scala

Why scala● Hybrid programming language● Statically typed● Runs on the jvm● Can execute java code

Page 22: Functional programming in Scala

Basics of Scala

Page 23: Functional programming in Scala

Everything is an Object● Supports object oriented programming● Including primitive types, everything in scala is an object

Example:

● val x = 10● x.toString()

Page 24: Functional programming in Scala

Statically Typed Language● var message = “hello”● message = “bye”● message = 100 //compilation error

● def abs(x:Int) : Int = { ??? }● abs(“100”) //compilation error

Page 25: Functional programming in Scala

Type Inference● val employeeName : String = “Joy”● val department = “HR” //Type inferred as String● val age = 35 //Type inferred as Int

Page 26: Functional programming in Scala

Collections● List,Set,Map etc..● Mutable● Immutable● Functional API

Example:

val integerList = List(1,2,3)

Page 27: Functional programming in Scala

Functional Aspect of Scala

Page 28: Functional programming in Scala

Operators are also a FunctionFor example

● val sum = 2 + 3

Is same as,

● val sum = 2.+(3) //because ‘+’ operator here is a function

Page 29: Functional programming in Scala

Functions in Scala

● Higher order function● Anonymous function● Currying● Tail recursion

Page 30: Functional programming in Scala

Defining a Function in Scala● Defining a function

In Scala -

def sum(x:Int,y:Int) : Int = x+y

In Java -

public int sum(int x,int y){

return x+y;

}

Page 31: Functional programming in Scala

Assigning function to variableExample :

def add = (x:Int,y:Int) => x+y

add(2,3) //should return 5

Page 32: Functional programming in Scala

Higher Order FunctionsFunction that takes functions as a parameters or return function as a result is called higher order functions

Example : com.ganesh.functions.HigherOrderFunctions.scala

Page 33: Functional programming in Scala

Anonymous FunctionScala provides a relatively lightweight syntax for defining anonymous functions.

Example:

(x: Int) => x + 1

Shorthand for above function is,

new Function1[Int, Int] {

def apply(x: Int): Int = x + 1

}

Page 34: Functional programming in Scala

CurryingCurrying allows to turn a function that expects two arguments into a function that expects only one, and that function returns a function that expects the second argument. Creating basically a chain of functions.

Example : com.ganesh.functions.Currying.scala

Page 35: Functional programming in Scala

Implicit ParametersThe final parameter list on a method can be marked implicit, which means the values will be taken from the context in which they are called.

● It means that if no value is supplied when called, the compiler will look for an implicit value and pass it in for you.

● Implicits are useful in defining default implementations available. When you need a custom implementation, you can pass one in explicitly.

Example : com.ganesh.implicits.Implicits.scala

Page 36: Functional programming in Scala

Tail Recursion● Tail recursion is a special kind of recursion where the recursive

call is the very last thing in the function.● tail-recursive function will only use a single stack frame as

opposed to hundreds or even thousands in case of normal recursive function.

● Tail recursion is much faster because it executes using single stack frame

Example : com.ganesh.functions.TailRecursion.scala

Page 37: Functional programming in Scala

Transformation on CollectionsWe can perform different transformations on collection using collection API.

Example:

com.ganesh.transformations.SimpleTransformations.scala

com.ganesh.transformations.AdvancedTransformations.scala

Page 38: Functional programming in Scala

Error HandlingScala does not have checked exceptions like Java, so you can't do something like this to force a programmer to deal with an exception.

Example :

com.ganesh.exceptionhandling.ExceptionThrowing.scala

com.ganesh.exceptionhandling.UsingOptions.scala


Recommended