Prolog/Search techniques

Prolog's default search algorithm is depth-first search (DFS), which is sometimes not convenient: DFS doesn't always find the solution for all problems, and when it does, it might not find the optimal solution.

Let's say we want to find the shortest path through a directed graph with nodes represented by symbols and arc by the predicate. Then we can easily implement iterative deepening search to find the shortest path:

backtracks over paths, ordered by length, if at least one path exists. Let's try it out:

How this works: when  is called with a variable first argument, it generates a list of the desired length containing fresh variables. When, in addition, the second argument is a variable, it backtracks over all possible lengths starting at zero and stepping by one. The helper predicate  is called each time with a fixed path length.