simple tail call optimization and stack safety for Java

Related tags

Development tail
Overview

com.github.kag0.tail

simple tail call optimization for Java

enables infinitely deep tail recursive calls without throwing a StackOverflowError

no transitive dependencies

Install

add the jitpack repository

<repositories>
...
  <repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
  </repository>
...
</repositories>

add the dependency

<dependencies>
...
  <dependency>
    <groupId>com.github.kag0</groupId>
    <artifactId>tail</artifactId>
    <version>Tag</version>
  </dependency>
...
</dependencies>

Use

import com.github.kag0.tail.Tail;
import static com.github.kag0.tail.Tail.*;

Tail<Void> infiniteLoop(int i) {
  System.out.println("Loop " + i + ", stack still intact!");
  return call(() -> infiniteLoop(i + 1));
}

infiniteLoop(0).evaluate();

Example: tail optimizing factorial computation

un-optimized first version

let's start with a simple recursive method to compute the nth factorial. this code will throw a StackOverflowError for large values of n.

long factorial(long n) {
  if(n == 1) return 1;
  else return n * factorial(n - 1);
}

move the recursive call into the tail position

the tail position is just another way of saying "the last thing you do before the return".

long factorial(long fact, long n) {
  if(n.equals(1)) return fact;
  return factorial(fact * n, n - 1);
}

this may require a slight refactor, usually to add an additional parameter to accumulate progress.

wrap the return type in Tail

this will enforce that the recursive call is in the tail position.

Tail<Long> factorial(long fact, long n)

wrap base cases with done

if(n.equals(0)) return done(fact);

wrap recursive calls with call

return call(() -> factorial(fact * n, n - 1));

profit

call .evaluate() on the invocation of your method.

factorial(1, Long.MAX_VALUE).evaluate();

recursive methods no longer blow the stack.
note that if you skip the 'move the recursive call into the tail position' step, the code will not compile because the method is not tail recursive and therefore not stack safe. thanks to Tail that is covered by type safety.

making safe recursive calls outside the tail position

in addition to making tail recursion safe, we can also use trampolining to enable recursive methods that would otherwise be tricky to make tail recursive.

to do this, just use .flatMap to chain two calls together.
for example

Tail<Integer> ackermann(int m, int n) {
  if(m == 0) 
    return done(n + 1);
  if(m > 0 && n == 0) 
    return call(() -> ack(m - 1, 1));
  if(m > 0 && n > 0) 
    return call(() -> ack(m, n - 1)).flatMap(nn -> ack(m - 1, nn));
  throw new IllegalArgumentException();
}

Benchmarks

You might also like...

Implementation of Greedy Particle Swarm Optimization, HSGA and Hybrid(GA+PSO) for the purpose of Task Scheduling in cloud computing environment using CloudSim

Implementation of Greedy Particle Swarm Optimization, HSGA and Hybrid(GA+PSO) for the purpose of Task Scheduling in cloud computing environment using CloudSim

Dec 18, 2022

Generate all call graph for Java Code.

Generate all call graph for Java Code.

README-en.md 1. 前言 在很多场景下,如果能够生成Java代码中方法之间的调用链,是很有帮助的。 IDEA提供了显示调用指定Java方法向上的完整调用链的功能,可以通过“Navigate - Call Hierarchy”菜单(快捷键:Ctrl+Alt+H)使用;Eclipse也提供

Jan 6, 2023

An open-source OTP & Call flooding android application with unlimited sending capability.

An open-source OTP & Call flooding android application with unlimited sending capability.

Tsunami v1.3 An open-source SMS & Call flooding Android application with unlimited OTP bombing capability 📝 Notes ⚙ Click here for App Usage Guide Th

Jan 2, 2023

A simple tool to get method stack

A simple tool to get method stack

Jan 17, 2022

The goal of the project is to create a web application using Java EE and database (PostgreSQL) without connecting a modern technology stack like spring boot and hibernate

The goal of the project is to create a web application using Java EE and database (PostgreSQL) without connecting a modern technology stack like spring boot and hibernate

About The Project SignIn page SignUp page Profile page The goal of the project is to create a web application using Java EE and database (PostgreSQL)

Mar 23, 2022

Ninja is a full stack web framework for Java. Rock solid, fast and super productive.

_______ .___ _______ ____. _____ \ \ | |\ \ | | / _ \ / | \| |/ | \ | |/ /_\ \ / | \

Jan 5, 2023

Base classes and utilities for Java Carbyne Stack service clients

Carbyne Stack Java HTTP Client This project provides common functionality for the Java-based HTTP clients for the Carbyne Stack microservices. License

Oct 15, 2022

In this course, we will learn how to build a complete full-stack web application using Spring boot as backend and React (React Hooks) as frontend

In this course, we will learn how to build a complete full-stack web application using Spring boot as backend and React (React Hooks) as frontend. We will use MySQL database to store and retrieve the data.

Dec 22, 2022

Full Stack Employee Management Application Using ReactJS and Spring Boot

Full Stack Employee Management Application Using ReactJS and Spring Boot Tech We Used ReactJs Spring Boot MySql Database Spring Security REST API Feat

Nov 18, 2022

DSMovie is a full stack web and mobile application built during Spring React Week, an event organized by DevSuperior

DSMovie is a full stack web and mobile application built during Spring React Week, an event organized by DevSuperior

projeto-DSMovie Sobre o projeto DSMovie é uma aplicação full stack web e mobile construída durante a Semana Spring React, evento organizado pela DevSu

Apr 18, 2022

An Intuitive, Lightweight, High Performance Full Stack Java Web Framework.

mangoo I/O mangoo I/O is a Modern, Intuitive, Lightweight, High Performance Full Stack Java Web Framework. It is a classic MVC-Framework. The foundati

Oct 31, 2022

Desafio numero 015 correspondiente al finalización del curso 01 de la carrera Java Full Stack de la academia Desafío LATAM

DesafioFinalProgramacionBasicaJava Desafio numero 015 correspondiente al finalización del curso 01 de la carrera Java Full Stack de la academia Desafí

Feb 17, 2022

Your window into the Elastic Stack

Kibana Kibana is your window into the Elastic Stack. Specifically, it's a browser-based analytics and search dashboard for Elasticsearch. Getting Star

Jan 2, 2023

Turn -XX:+TraceBytecodes output into a FlameGraph compatible stack format

Turn -XX:+TraceBytecodes output into a FlameGraph compatible stack format

A tool to turn the output of -XX:+TraceBytecodes (a JDK debug-only feature to print every bytecode executed by the interpreter) into a simple stack fo

Dec 11, 2022

Spring Boot Full Stack with React for Professionals

Spring Boot Full Stack with React for Professionals

Spring Boot allows to take an idea/prototype and turn it into a real thing in matters minutes hours of months and years. A lot of companies use Spring Boot because it's easy to setup, learn and write code very fast without having to setup the low level platform code

Dec 29, 2022

Spring Boot Full Stack with React for Professionals

Spring Boot Full Stack with React for Professionals

Spring Boot allows to take an idea/prototype and turn it into a real thing in matters minutes hours of months and years. A lot of companies use Spring Boot because it's easy to setup, learn and write code very fast without having to setup the low level platform code. Recently, Netflix has decided to switch their entire backend to Spring Boot.

Mar 25, 2021

Minecraft mod to change the stack size of all items. Fabric 1.17

Minecraft mod to change the stack size of all items. Fabric 1.17

Stacker Minecraft mod to change the stack size of all items. For Fabric 1.17 Note: This mod has a config that defaults to 64. Change it to be whatever

Sep 25, 2022

Carbyne Stack MP-SPDZ Integration Utilities

Carbyne Stack MP-SPDZ Integration Utilities This project provides utilities for using MP-SPDZ in the Carbyne Stack microservices. License Carbyne Stac

Oct 15, 2022

Command Line Interface to interact with Carbyne Stack Virtual Clouds

Carbyne Stack Command Line Interface This is a CLI tool to communicate with the Carbyne Stack services. DISCLAIMER: The Carbyne Stack CLI is alpha sof

Oct 15, 2022
Java 1-15 Parser and Abstract Syntax Tree for Java, including preview features to Java 13

JavaParser This project contains a set of libraries implementing a Java 1.0 - Java 14 Parser with advanced analysis functionalities. This includes pre

JavaParser 4.5k Jan 5, 2023
Project on End to End CI/CD pipeline for java based application using Git,Github,Jenkins,Maven,Sonarqube,Nexus,Slack,Docker and Kuberenets with ECR as private docker registry and Zero Downtime Deployment

Project on End to End CI/CD pipeline for java based application using Git,Github,Jenkins,Maven,Sonarqube,Nexus,Slack,Docker and Kuberenets with ECR as private docker registry and Zero Downtime Deployment.

NITHIN JOHN GEORGE 10 Nov 22, 2022
Java library for handling exceptions in concise, unified, and architecturally clean way.

NoException NoException is a Java library for handling exceptions in concise, unified, and architecturally clean way. System.out.println(Exceptions.lo

Robert Važan 79 Nov 17, 2022
Dynamic Code Evolution VM for Java 7/8

NEWS: Dcevm-11 on Trava OpenJDK There is a new distribution channel for DCEVM-11 binaries on - TravaOpenjdk! DCEVM This project is a fork of original

null 1.6k Dec 28, 2022
A library that simplifies error handling for Functional Programming in Java

Faux Pas: Error handling in Functional Programming Faux pas noun, /fəʊ pɑː/: blunder; misstep, false step Faux Pas is a library that simplifies error

Zalando SE 114 Dec 5, 2022
Java unlimited redefinition of classes at runtime.

Hotswap Agent This is an overview page, please visit hotswapagent.org for more information. Overview Java unlimited runtime class and resource redefin

null 1.9k Dec 30, 2022
SneakyThrow is a Java library to ignore checked exceptions

SneakyThrow SneakyThrow is a Java library to ignore checked exceptions. You can integrate it using maven: <dependency> <groupId>com.rainerhahnekamp<

Rainer Hahnekamp 73 Nov 8, 2022
By this package we can get sim info, call logs and sms logs.Also we can find for specific sim info and call logs as well.

sim_sms_call_info A new flutter plugin project. Getting Started This project is a starting point for a Flutter plug-in package, a specialized package

 Hasib Akon 3 Sep 17, 2022
jsoup: the Java HTML parser, built for HTML editing, cleaning, scraping, and XSS safety.

jsoup: Java HTML Parser jsoup is a Java library for working with real-world HTML. It provides a very convenient API for fetching URLs and extracting a

Jonathan Hedley 9.9k Jan 4, 2023
This project uses the artificial potential field method to realize the path planning of the robot, and completes the trajectory optimization through other settings. It can also be combined with laser SLAM, target recognition and other technologies for path planning.

FRCAutoDriver 项目说明 Project Instruction 本项目利用人工势场法,实现机器人的路径规划,并通过其他设置完成轨迹优化,还可以结合激光SLAM、目标识别等技术进行路径规划 This project uses the artificial potential field

ZhangzrJerry 2 Sep 9, 2022