# Trampoline
A trampoline is a way of implementing [[Tail-Call Optimization]] in languages that do not supported it (such as C#).
This technique is not particularly popular in the object oriented programming community (for no good reason) due to the stigma related to [[Recursion]]. This is another good example of how [[Conservatism Stymies Progress]].
The trampoline is a [[Free Monad]] whose functor is a function that takes no parameters and returns the functor type.
## Trampoline in C# 
```csharp
public record Trampoline<T>
{
    public record DoneCase(T Result) : Trampoline<T>;
    public record ContinueCase(Func<Trampoline<T>> Next) : Trampoline<T>;
    private Trampoline() { }
	public static Trampoline<T2> Bind<T1, T2>(Func<T1, Trampoline<T2>> f, Trampoline<T1> x) =>  
	    x switch  
	    {  
	        Trampoline<T1>.DoneCase { Result: var result } => f(result),  
	        Trampoline<T1>.ContinueCase { Next: var next } =>  
	            new Trampoline<T2>.ContinueCase(() => Bind(f, next())),  
	        _ => throw new ArgumentOutOfRangeException()  
	    };
    public T Run()
    {
        Func<Trampoline<T>> current = () => this;
        while (true)
        {
            switch (current())
            {
                case ContinueCase { Next: var next }:
                    current = next;
                    break;
                case DoneCase { Result: var result }:
                    return result;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}
public static class Trampoline
{
    public static Trampoline<T> Done<T>(T result) =>
        new Trampoline<T>.DoneCase(result);
    public static Trampoline<T> Continue<T>(Func<Trampoline<T>> jumper) =>
        new Trampoline<T>.ContinueCase(jumper);
}
```