listlength(, 0). listlength([Head | Tail], Length) :- listlength(Tail, TailLength), Length is TailLength + 1.The rule is to align heads of rules against the left margin, and to indent body clauses, normally all by the same amount. Sometimes further indentation is needed, for example if the code involves a complex term that won't fit on one line. In this case, you would indent the term to exhibit its structure.
… book( title('The Strange Case of Dr Jekyll and Mr Hyde and Other Tales of Terror'), author(given_names(['Robert', 'Louis']), surname('Stevenson') ), publisher('Penguin Books') ), …
Sometimes the indentation rules can be bent: for example, it is not unusual to put on a single line, a rule with a body that contains just a single (short) clause.
happy(Person) :- rich(Person).
Comments on indented code should also be indented, if they can't be fitted on the same line as the code.
% sum_even_elements(+ListOfNumbers, -Sum): compute Sum of even items in ListOfNumbers sum_even_elements(, 0). % base case sum_even_elements([FirstNum | Rest], Sum) :- % check whether FirstNum is even 0 is FirstNum mod 2, % if we get here it was even, so process rest of list and add FirstNum to result sum_even_elements(Rest, SumForRest), Sum is FirstNum + SumForRest. sum_even_elements([FirstNum | Rest], Sum) :- % this rule handles the case where FirstNum is /not/ even 0 =\= FirstNum mod 2, sum_even_elements(Rest, Sum).This example is more heavily commented than necessary, in order to demonstrate the commenting convention.
See also comments and white space.