DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
What's in store for DevOps in 2023? Find out today at 11 am ET in our "DZone 2023 Preview: DevOps Edition!"
Last chance to join
  1. DZone
  2. Coding
  3. Java
  4. Functional Programming: Recursion

Functional Programming: Recursion

As we dive deeper into functional programming techniques, let's talk about functional loops and recursion (including head and tail recursion).

Christian Panadero user avatar by
Christian Panadero
·
Jan. 24, 18 · Tutorial
Like (20)
Save
Tweet
Share
18.38K Views

Join the DZone community and get the full member experience.

Join For Free

Recursion is a technique that allows us to break down a problem into smaller pieces. This technique allows us to remove some local side effects that we perform while writing looping structures and also makes our code more expressive and readable. In this post, we will see why it is a very useful technique in functional programming and how it can help us.

Functional Loops

In the function that we wrote in the previous post:

def sumIntsTo(i: Int) = {
  var result = 0
  0 to i foreach((i) => result = result + i)
  result
}


You could notice that there is a side effect in that imperative-like loop. We are assigning the result of the computation to an accumulator because foreach is a function that returns Unit. Or in other words, it does not return anything, so we don't have any other choices. That foreach method, therefore, is a statement. We say that a statement is a block of code that can be executed but not reduced. On the other hand, we say that a block of code that can be reduced is an expression.

Head Recursion

The first technique that we are going to use is called head recursion. Let's translate the previous function to a head recursive function:

def sumIntsToRecursive(i: Int) : Int =
  if (i == 0) 0 else i + sumIntsToRecursive(i - 1)


This function does not have any side effects. Internally, it calculates a sum until we reach the base case, which is 0. Here is the stack trace for sumIntsToRecursive(5):

sumIntsToRecursive(5)
5 + sumIntsToRecursive(4)
5 + (4 + sumIntsToRecursive(3))
5 + (4 + (3 + sumIntsToRecursive(2)))
5 + (4 + (3 + (2 + sumIntsToRecursive(1))))
5 + (4 + (3 + (2 + (1 + sumIntsToRecursive(0)))))
5 + (4 + (3 + (2 + (1 + 0))))
> 15


We can say that the recursive calls occur before the computation, or at the head. That means that after the recursive call we can have other blocks to evaluate, or like in this case, we evaluate the first sum after all the consequent evaluations are reduced.

You could see as well that we have to keep the state of the current computation until we finish evaluating the stack, so in the last step we will end up holding: 5 + 4 + 3 + 2 + 1 and then we will evaluate the last case to finish up with the computation of all the values that we had in the intermediate steps.

Holding this state can be a problem, especially if we deal with a large set of numbers. If we try to evaluate the previous function passing Integer.MAX_VALUE as the argument, we will see that the function crashes and gives us a StackOverflowException. Even if we achieved our initial purpose of not having side effects, we do have one if the number is too large to be evaluated. That leads us to the next technique, tail recursion.

Tail Recursion

The only difference between head and tail recursion is that the recursive calls occur after the computation, or at the tail. Let's translate the previous function to a tail recursive function:

def sumIntsToTailRecursive(i: Int) : Int = {
    @tailrec
    def go(i: Int, acc: Int): Int = {
      if (i == 0) acc
      else {
        val nextI = i - 1
        val nextAcc = acc + i
        go(nextI, nextAcc)
      }
    }
    go(i, 0)
}


As you could notice the last call in the method is the tail recursive call, we need to make the computations before invoking it. That leads us to the following stack trace:

go(5, 0)
go(4, 5)
go(3, 9)
go(2, 12)
go(1, 14)
go(0, 15)
> 15


As you could notice, we only have to hold the previous intermediate state, but not all the states previous to the current one. If we execute this function with the argument Integer.MAX_VALUE, we will see that it completes just fine.

In modern languages like Scala, Kotlin, etc., tail recursive calls are converted to imperative loops at compile time to optimize the code. In Scala, when we write a tail recursive function, we can annotate the recursive method with @tailrec. If we do so, and the function is not tail recursive, we will have an error at compile time.

I recommend that you practice writing recursive functions, as they are a common technique in functional programming. Fibonacci numbers, a bowling score calculator or the Pascal triangle are good exercises to get used to it.

Functional programming

Published at DZone with permission of Christian Panadero, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Distributed SQL: An Alternative to Database Sharding
  • Using QuestDB to Collect Infrastructure Metrics
  • Public Cloud-to-Cloud Repatriation Trend
  • Exploring the Benefits of Cloud Computing: From IaaS, PaaS, SaaS to Google Cloud, AWS, and Microsoft

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: