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

Explanation of a Prolog algorithm to append two lists together

First, let’s translate the clauses into something more understandable: append([], List, List) :- !. can be written append([], List2, Result) :- Result = List2, !. and append([H|L1], List2, [H|L3]) :- append(L1, List2, L3). can be written append(List1, List2, Result) :- List1 = [Head1 | Tail1], Result = [HeadR | TailR], Head1 = HeadR, append(Tail1, List2, … 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

Are any JavaScript engines tail call (TCO) optimized?

The ECMAScript 4 specification was originally going to add support for TCO, but it was dropped: No more tail calls in JavaScript? As far as I know, no widely-available implementations of JavaScript currently do automatic TCO. This may be of use to you, though: Tail Call Optimization Essentially, using the accumulator pattern accomplish the same … Read more

foldl is tail recursive, so how come foldr runs faster than foldl?

Welcome to the world of lazy evaluation. When you think about it in terms of strict evaluation, foldl looks “good” and foldr looks “bad” because foldl is tail recursive, but foldr would have to build a tower in the stack so it can process the last item first. However, lazy evaluation turns the tables. Take, … Read more