November 25, 2025
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).