Date post: | 21-Feb-2017 |
Category: |
Data & Analytics |
Upload: | datamantra |
View: | 199 times |
Download: | 0 times |
Functional programming in Scala
https://github.com/ganeshayadiyala/functional-programming-in-scala
● Ganesha Yadiyala
● Big data consultant at
datamantra.io
● Consult in spark and scala
Agenda● Programming paradigms● Functional Programming● Advantages of FP● History of Scala ● Basics of scala● Functional Aspect of Scala
Programming Paradigms
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
Imperative ProgrammingImperative programming is a programming paradigm that uses statements that change a program's state.
Example :
● C#● C++● Java
Functional ProgrammingA programming style that models computation as the evaluation of expression.
Example:
● Haskell● Erlang● Lisp● Clojure
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
Example :
Statement -> boolean isEven = true
if(x%2 == 0)
isEven = true
else
isEven = false
Functional Programming
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
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
Characteristics of FP● Immutable data● Lazy evaluation● No side effects● Referential transparency● Functions are first class citizens
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
Advantages of FP● Better modularity● Shorter code● Increased developer productivity● Less number of bugs● Perfect for distributed computing because of immutability● Easier debugging
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
History of 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
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
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
Why scala● Hybrid programming language● Statically typed● Runs on the jvm● Can execute java code
Basics of Scala
Everything is an Object● Supports object oriented programming● Including primitive types, everything in scala is an object
Example:
● val x = 10● x.toString()
Statically Typed Language● var message = “hello”● message = “bye”● message = 100 //compilation error
● def abs(x:Int) : Int = { ??? }● abs(“100”) //compilation error
Type Inference● val employeeName : String = “Joy”● val department = “HR” //Type inferred as String● val age = 35 //Type inferred as Int
Collections● List,Set,Map etc..● Mutable● Immutable● Functional API
Example:
val integerList = List(1,2,3)
Functional Aspect of Scala
Operators are also a FunctionFor example
● val sum = 2 + 3
Is same as,
● val sum = 2.+(3) //because ‘+’ operator here is a function
Functions in Scala
● Higher order function● Anonymous function● Currying● Tail recursion
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;
}
Assigning function to variableExample :
def add = (x:Int,y:Int) => x+y
add(2,3) //should return 5
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
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
}
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
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
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
Transformation on CollectionsWe can perform different transformations on collection using collection API.
Example:
com.ganesh.transformations.SimpleTransformations.scala
com.ganesh.transformations.AdvancedTransformations.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
References● https://www.coursera.org/learn/progfun1/ - Scala course by
Martin Odersky ● http://www.dipmat.unict.it/~barba/PROG-LANG/PROGRAMMI-
TESTI/READING-MATERIAL/ShortIntroFPprog-lang.htm - Functional programming and lambda calculus
● Functional Programming in Scala