FUNCTIONAL PROGRAMMING
Functional programming is a style of programming that emphasizes writing
applications using only pure functions and immutable values.
PURE
FUNCTIONS
How we know that our code is pure functional or Impure , I’m
putting some points on consideration
·
The
function’s output depends only on its input variables
·
It
doesn’t mutate any hidden state
·
It
doesn’t have any “back doors”: It doesn’t read data from the outside world
(including the console, web services, databases, files, etc.), or write data to
the outside world
·
Example
of pure function:
scala.math._ package (abs,Ceil,max,min),Scala String Method(isEmpty,length,substring),Scala
Collection(map,filter,drop)
Key
Consideration:
A pure
function is a function that depends only on its declared inputs
and its internal algorithm to produce its output. It does not read any other
values from “the outside world” — the world outside of the function’s scope —
and it does not modify any values in the outside world.
impure functions:
the
following functions are impure because they
violate the definition.
The
foreach
method on collections classes is impure
because it’s only used for its side effects, such as printing to STDOUT.
A great hint that
foreach
is impure is
that it’s method signature declares that it returns the type Unit
. Because it
returns nothing, logically the only reason you ever call it is to achieve some
side effect. Similarly, any method that
returns Unit
is going to
be an impure function.getDayOfWeek
, getHour
, and getMinute
are all
impure because their output depends on something other than their input
parameters.
In general, impure functions do one or more of these
things:
·
Read
hidden inputs, i.e., they access variables and data not explicitly passed into
the function as input parameters
·
Write
hidden outputs
·
Mutate
the parameters they are given
·
Perform
some sort of I/O with the outside world
impure functions are
needed …
Of course an application isn’t very useful if it can’t read
or write to the outside world,
Write the core
of your application using pure functions, and then write an impure “wrapper”
around that core to interact with the outside world. If you like food
analogies, this is like putting a layer of impure icing on top of a pure cake.
Key Consideration for Functional programming:
Key Consideration for Functional programming:
- Functional programmers don’t use null values
- A main replacement for null values is to use the Option/Some/None classes
- Common ways to work with Option values are
match
andfor
expressions - Options can be thought of as containers of one item (
Some
) and no items (None
) - You can also use Options when defining constructor parameters