Flatten Nested Lists in Prolog

A follow up to my last post, here’s how you flatten a list in prolog.

% Base cases, empty lists match empty lists
flatten([],[]).

% Pick the head and tail out of a list
flatten([H1|T1],L2):-
  % Try and flatten the head, if it fails (because the head is not a list), wrap that element in a list).
  (flatten(H1,H1Flat); H1Flat = [H1]),
  (flatten(T1,T1Flat); T1Flat = [T1]),

  % Join our two flattened lists together
  append(H1Flat,T1Flat,L2).

Want to comment? Follow @blog@jimkubicek.com on Mastodon and reply to this post. Search for this URL in your Mastodon client:

https://jimkubicek.com/2025/11/25/flatten-nested-lists-in-prolog/