Comments for cut (!), do you have guidelines

When using cut (!) in code it is sometimes beneficial to add a comment to explain why the cut is there.

After a while one learns that many of the cuts (!) are basically the same.

Recently in looking at source for split/3 the cut has the comment % optimization and that looks simple enough to explain why the cut is there.

So I was wondering if others have a set of guidelines they use for comments with cuts. I currently don’t have any so my comments for cut are all over the place and that is a bad habit I need to break.

EDIT

Why such a question?

In the old days of coding on keypunch machines there was basically a line and simple short comments.

Then as time evolved developers would add comments for documentation, write some examples, add notes about when or how the method should work, and so on.

If you notice most of those comments are now full blown extensions of the language and related applications, e.g.

Documentation comments –> PLDoc, JavaDoc (Comparison of documentation generators)
Method/Predicate examples –> Unit testing (SWI-Prolog) (Java) (List of unit testing frameworks)
When to use method/predicate –> Attributes, Metadata, RTTI
Works with –> Modules

Besides comments, my personal practice is to write green cuts in the same line after the goal whose choice-points are being discarded and always write red cuts in a separate line. One example of a green cut layout would be:

msort([], []) :- !.
msort([X], [X]) :- !.
msort([X, Y| Xs], Ys) :-
	split([X, Y| Xs], X1s, X2s),
	msort(X1s, Y1s),
	msort(X2s, Y2s),
	merge(Y1s, Y2s, Ys).

An example red cut layout (missing a comment) would be:

memberchk(Element, [Element| _]) :-
	!.
memberchk(Element, [_| List]) :-
	memberchk(Element, List).

This helps me in reading my own old code but it would be moot in any scenario where code reformatters are used or could be used. So, always comment at least red cuts is the best advice. Discounting not using cuts in the first place, that is.

3 Likes

Interesting thought! In my experience the mode documentation line claiming instantiation and determinism is key to place and understand cuts.