Generate tail call opcode

C# compiler does not give you any guarantees about tail-call optimizations because C# programs usually use loops and so they do not rely on the tail-call optimizations. So, in C#, this is simply a JIT optimization that may or may not happen (and you cannot rely on it). F# compiler is designed to handle functional … Read more

F# Tail Recursive Function Example

Start with a simple task, like mapping items from ‘a to ‘b in a list. We want to write a function which has the signature val map: (‘a -> ‘b) -> ‘a list -> ‘b list Where map (fun x -> x * 2) [1;2;3;4;5] == [2;4;6;8;10] Start with non-tail recursive version: let rec map … Read more

When is tail recursion guaranteed in Rust?

Shepmaster’s answer explains that tail call elimination is merely an optimization, not a guarantee, in Rust. But “never guaranteed” doesn’t mean “never happens”. Let’s take a look at what the compiler does with some real code. Does it happen in this function? As of right now, the latest release of Rust available on Compiler Explorer … Read more

Are there problems that cannot be written using tail recursion?

Yes, actually you can take some code and convert every function call—and every return—into a tail call. What you end up with is called continuation-passing style, or CPS. For example, here’s a function containing two recursive calls: (define (count-tree t) (if (pair? t) (+ (count-tree (car t)) (count-tree (cdr t))) 1)) And here’s how it … Read more

tech