Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* See http://stackoverflow.com/a/39350385/1281433 */
- public class Trampoline {
- /**
- * State of a computation for a trampoline.
- *
- * @param <T> the type of value
- */
- public interface TrampolineState<T> {
- /**
- * Returns whether the state is a finished state.
- *
- * @return whether the state is a finshed state
- */
- boolean isFinished();
- /**
- * Returns the value, if this state is finished.
- *
- * @return the value
- * @throws IllegalStateException if the state is not finished
- */
- T getValue() throws IllegalStateException;
- /**
- * Returns the next state, if this state is not finished.
- *
- * @return the next state
- * @throws IllegalStateException if the state is finished
- */
- TrampolineState<T> getNext() throws IllegalStateException;
- }
- /**
- * Executes a trampolined state and its successors until a finished state is
- * reached, and then returns the value of the finished state.
- *
- * @param state the state
- * @return the value
- */
- public <T> T trampoline(TrampolineState<T> state) {
- while (!state.isFinished()) {
- state = state.getNext();
- }
- return state.getValue();
- }
- /**
- * Returns the state for for sum computation.
- *
- * @param x the augend
- * @param y the addend
- * @return the state
- */
- private TrampolineState<Integer> getSumTrampolineState(int x, int y) {
- return new TrampolineState<Integer>() {
- @Override
- public boolean isFinished() {
- return x == 0;
- }
- @Override
- public Integer getValue() {
- if (!isFinished()) {
- throw new IllegalStateException();
- }
- return y;
- }
- @Override
- public TrampolineState<Integer> getNext() {
- if (isFinished()) {
- throw new IllegalStateException();
- }
- return getSumTrampolineState(x - 1, y + 1);
- }
- };
- }
- /**
- * Returns a sum, computed by a trampolined computation.
- *
- * @param x the augend
- * @param y the addend
- * @return the sum
- */
- public int sum(int x, int y) {
- return trampoline(getSumTrampolineState(x, y));
- }
- }
Add Comment
Please, Sign In to add comment