Because of the way that free variables interact with bagof/3, I think this is better:
bagof_fail_empty(Template, Goal, Bag) :-
( bagof(Template, Goal, Bag)
*-> true
; Bag = []
).
As @jan says, doing this indicates a misunderstanding of bagof/3, but sometimes it’s convenient to have a predicate always return a value rather than handle a failure case - for example, if I want to do further processing on each item in the “Bag”.
Similarly, whatever the theoretical underpinnings of “reverse” of an empty list might be, it’s sometimes convenient to generate a list in reverse order then use reverse/3, so it simplifies the code if reverse/3 can handle []
and [_]
just like any other list.
@boris - do you have any suggestions on how to write predicates so that they generate lists in correct order, without using append/3? Sometimes I have no problems doing this; but at other times (e.g., when using a list as an accumulator, or using foldl
), I just give up and use reverse/3 on the result. I suppose this requires using difference lists, but sometimes getting them right (whithout using DCGs) is too difficult for me. “When you are a Bear of Very Little Brain, and you Think of Things, you find sometimes that a Thing which seemed very Thingish inside you is quite different when it gets out into the open and has other people looking at it.”