Code Layout for Lists, Dicts and Module Predicates

Many organizations and some languages have definitive style-guides describing how an author should layout their code to improve readability. The rules are designed to be easy on the eye and provide consistency for multi-author projects. For better or worse, Prolog seems to be spared from an authoritative prescriptive document, such as Python's PEP8. In this post I'll opine about some practices that you may find useful.

I'll skip the common rules, such as spaces after commas and colons: foo(A, B), foo{a: b} rather than the squashed foo(A,B), foo{a:b}, as these rules are common to the style-guides of most languages and I'm going to assume if you're programming in Prolog you already have a decent grounding. Instead I'll focus on a couple of things unique to Prolog or that are a little more unusual.


In many languages, a trailing comma is valid syntax in a list: [1, 2, 3,], not so in Prolog. Therefore, to make lists easy to edit and read, we can borrow a format used in Haskell.

This layout, although not immediately obvious, makes it relatively simple to add and remove items from the list without making any silly mistakes with the commas. The indentation makes it easy to read, you'll find your eye ignoring the symbols and just reading down the list.


The same idea as used in lists is applied to dictionaries.

Declaring Modules

The list format gives rise to a beautiful way to write your module declarations that also makes it easy to add and remove exported predicates. Indentation has been used to show to what the list belongs, the closing bracket is back on the base column to make the end obvious. This same pattern can be applied to other complex facts, shown by frame/2.

Importing Modules

When importing predicates from modules it is good practice to explicitly name them. Named imports help another author (including future you) browsing your code, it's easier for them to find where that predicate came from. This is the same reason your filenames should mirror your module names. It also helps learners to navigate the library better.


I hope this is useful for you, I certainly find it saves me bother when editing and reading code.