Functional Programming with Java Tutorial
Selected Reading
- Discussion
- Resources
- Quick Guide
- Fixed Length Streams
- Infinite Streams
- Terminal methods
- Intermediate Methods
- Exception Handling
- Type Inference
- Pure Functions
- First Class Functions
- Returning a Function
- High Order Functions
- Collections
- Constructor References
- Method References
- Functional Interfaces
- Default Methods
- Lambda Expressions
- Reducing
- Currying
- Closure
- Optionals & Monads
- Parallelism
- Recursion
- Persistent Data Structure
- Eager vs Lazy Evaluation
- Functional Composition
- Functions
- Overview
- Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Pure Functions
Functional Programming - Pure Function
A function is considered as Pure Function if it fulfils the following two conditions −
It always returns the same result for the given inputs and its results purely depends upon the inputs passed.
It has no side effects means it is not modifying any state of the caller entity.
Example- Pure Function
pubpc class FunctionTester { pubpc static void main(String[] args) { int result = sum(2,3); System.out.println(result); result = sum(2,3); System.out.println(result); } static int sum(int a, int b){ return a + b; } }
Output
5 5
Here sum() is a pure function as it always return 5 when passed 2 and 3 as parameters at different times and has no side effects.
Example- Impure Function
pubpc class FunctionTester { private static double valueUsed = 0.0; pubpc static void main(String[] args) { double result = randomSum(2.0,3.0); System.out.println(result); result = randomSum(2.0,3.0); System.out.println(result); } static double randomSum(double a, double b){ valueUsed = Math.random(); return valueUsed + a + b; } }
Output
5.919716721877799 5.4830887819586795
Here randomSum() is an impure function as it return different results when passed 2 and 3 as parameters at different times and modifies state of instance variable as well.
Advertisements