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
Recursion
Functional Programming with Java - Recursion
Recursion is calpng a same function in a function until certain condition are met. It helps in breaking big problem into smaller ones. Recursion also makes code more readable and expressive.
Imperative vs Recursive
Following examples shows the calculation of sum of natural numbers using both the techniques.
pubpc class FunctionTester { pubpc static void main(String[] args) { System.out.println("Sum using imperative way. Sum(5) : " + sum(5)); System.out.println("Sum using recursive way. Sum(5) : " + sumRecursive(5)); } private static int sum(int n){ int result = 0; for(int i = 1; i <= n; i++){ result = result + i; } return result; } private static int sumRecursive(int n){ if(n == 1){ return 1; }else{ return n + sumRecursive(n-1); } } }
Output
Sum using imperative way. Sum(5) : 15 Sum using recursive way. Sum(5) : 15
Using recursion, we are adding the result of sum of n-1 natural numbers with n to get the required result.
Tail Recursion
Tail recursion says that recursive method call should be at the end. Following examples shows the printing of a number series using tail recursion.
pubpc class FunctionTester { pubpc static void main(String[] args) { printUsingTailRecursion(5); } pubpc static void printUsingTailRecursion(int n){ if(n == 0) return; else System.out.println(n); printUsingTailRecursion(n-1); } }
Output
5 4 3 2 1
Head Recursion
Head recursion says that recursive method call should be in the beginning of the code. Following examples shows the printing of a number series using head recursion.
pubpc class FunctionTester { pubpc static void main(String[] args) { printUsingHeadRecursion(5); } pubpc static void printUsingHeadRecursion(int n){ if(n == 0) return; else printUsingHeadRecursion(n-1); System.out.println(n); } }
Output
1 2 3 4 5Advertisements