#Try to put every possible case into a single rule
Try to put every possible case into a single rule
The clean way to program in Prolog is to declare multiple rules for the same predicate. For example, a predicate to reverse a list with an accumulator would look like this:
r([],Z,Z). r([H|T],Z,R):-r(T,[H|Z],R). In Code-golf, we can remove the first rule, and add a ; at the end of the second rule to code the recursion end:
r([H|T],Z,R):-r(T,[H|Z],R);R=[H|Z]. We know that the first condition r(T,[H|Z],R) will fail if T is empty, i.e. if the recursion need to end and thus we can add our termination as an or clause after it.
The same principle works in a lot of situations. Note however that sometimes it is actually shorter to declare another rule rather than doing this.