Tree Breadth-First in Prolog

@Mathie Prolog’s ways of handling different cases is very confusing at first.

To illustrate, I’ll translate the JavaScript switch example found at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

The Prolog equivalent would look something like

fruit('Oranges') :- !,
    format("Oranges are $0.59 a pound.~n", []).

fruit(Fruit) :-
    member(Fruit, ['Mangoes', 'Papayas']), !,
    format("~w are $2.79 a pound.~n", [Fruit]).

fruit(Fruit) :-
   format("Sorry, we are out of ~w.~n", [Fruit]).

Edit As advised by @jan, I moved the cuts to immediately after the tests which check if Fruit matches that particularly case.

The exclamation mark ! (called cut in Prolog jargon) is akin to the break in the JavaScript example. If the first two predicates didn’t have the ! cut, ‘Oranges’ would match both the first and last predicate, and ‘Mangoes’ or ‘Papayas’ would match the second and third predicates. As does break, the ! tells the program not to continue trying to match further cases once one has succeeded, leaving the final uncut predicate as the default if none of the previous cases matched.

Back to my example:

The cut ! isn’t actually required in this case since the empty list wouldn’t match the next case depthfirst([Node|Frontier]) in any event. It is the recursive base case which calls the program to a halt by doing nothing (other than return true).

But telling it not to bother looking further if it has got to the end (empty list) might save an infinitismal amount of time and electricity.