Functional Programming, simplified

Preview:

Citation preview

FP, simplified for java programmers

Naveen Muguda

Programming Paradigms

• Wikipedia lists about 30+ paradigms

Programming Paradigms(..continued)

• Two paradigms are largely prevalent • Procedural (vast majority)

• Object Oriented (occasional)

• Functional (old kid making a come back)

Procedural

OO

Functional

Structures

procedures

functions

types

objects

Paradigm:Data

Shared/Hidden Mutable/Immutable

Procedural Shared Mutable

Object Oriented Hidden Mutable

Functional Shared Immutable

Paradigm: snippets

• Find elements of a list

Procedural find(list)

Object Oriented list.find(y)

Functional list.filter(x -> (x == y));

Snippets(..continued)

even list.filter(x -> (x % 2) == 0)

odd list.filter(x -> (x % 2) != 0)

prime list.filter(Primes::isPrime)

Multiple of list.filter(x -> isMultiple(x, 4))

Building block: Function

• Functions return value vs stack.push()

• Functions are methods which have no side effects vs list.add()

• Functions always return the same value for the same input vs stack.pop()

• Functions don’t access data in other contexts* vs list.size()

Side effects

• Have to be managed

• push():pop()

• lock():unlock()

• allocate():free()

Control abstractions

Have side effects Don’t have side effects

statement Expression

procedure function

Higher order functions

• x, f, f(x)

• filter(Predicate predicate)• …

• if(predicate.test(x) == true)• result.add(x)

Granularity

• filter(Predicate<X> predicate)

• map(Function<X, Y> mapper)

• fold(T zero, Bifunction<T, T>combiner)

parameterization

• fold(1, (x, y) -> (x * y))

• fold(0, (x, y) -> (x + y))

• fold(Integer.Minimum, (x, y)-> max(x, y))

composability

• f(g(h(x)))

• map(h).map(g).map(f)

• filter(m).find(f).map(g).orElse(y)

..benefits

• Functions are easier to reason

• Functions are modular

• Functions are safer

Monad

• wrap data

• accept a chain of functions

• create a chain of monads

• Provide utility around wrapped data

Monad(..continued)

• wrap

• map

• flatMap

Monads

Monad Value

Identity storage

Stream parallelising pipeline

Promise deferring pipeline execution

Optional creates non-null and null pipelines,provides null safety

Either creates two pipelines, usually happy path and other path, encapsulates concerns

Try Creates two pipelines, happy path and exception path, encapsulates concerns

Modularization in non-FP worldModularization in FP world

Where is FP being used?

• map/reduce

• Java Streams

• Reactive

• Spark

• Kafka

recommendations

• statements -> expressions

• procedures-> functions

• null check -> Optional

• if-else-> Either

• if-else-> ternary

• for-> stream

• try-catch-> Try

catch

• Sorting, inserting are all painful

• great for queries, figuring out for mutations

Recommended