A Lazy Sequence

List rotation in Prolog

I’m still dipping into logic programming intermittently. I’m still a tourist. Today I had reason to want to rotate a list – that is, take some number of items from the front, and append them to the back – and I couldn’t find a suitable predicate in the standard libray. My initial attempts to write the predicate myself were bad (leaning on functional and procedural definitions), and in googling I could only find other unsatisfying solutions.

list_rotation_list(List, N, Rot) :-
    length(N, Front),
    append(Front, Back, List),
    append(Back, Front, Rot).

Here, length is used to generate a “dynamic” pattern for pattern matching unification against the front of the list: it’s just a list of free variables of a specific length to pattern match the front of the input list. Then the relational behaviour of append unifies the actual values into Front and the remainder into Back, finally just running append again with the order flipped to generate Rot.


One of my friends described Prolog as a “puzzle box language”, and I think thats a great description; there’s something satisfacting in describing a predicate in a way that declaritively expresses the problem. Initially I didn’t think to use length, and wrote a bespoke – and terrible – predicate called free_list_ that did the job badly. This sort of turned-around way of thinking about problems is what I find makes Prolog so satisfying, and mind boggling, to learn and use.

7 August 2026