view 3-Prolog/day2-concat.pl @ 103:98be775c533c default tip

An odd "non-determinism" example from StackOverflow It is clever, but doesn't make much sense as to how it gets its results
author IBBoard <dev@ibboard.co.uk>
date Sun, 14 Jul 2019 13:44:13 +0100
parents 643eec1f9e3a
children
line wrap: on
line source

% Rewriting "append" from scratch as "concat"
% Append/3 is true when List1+List2 = List3. This can be used to:
%  * check whether two lists combine to a third (supply all args)
%  * combine lists (supply first two and a variable for the third)
%  * remove an item from a list (pass the first and third and the variable in 2)
%  * computing splits of the list (pass two variables and a list - possibly the least useful, normally)
%
% The following is written without looking at the code, just the list of features.

% Concat an empty list
concatenate(List1, List2, List3) :- List2 = [], List3 = List1.
% Concat one item from 1 on to 2
concatenate(List1, List2, List3) :- List1 = [Head1], List3 = [Head1|List2].
% Concat more items
concatenate(List1, List2, List3) :- List1 = [Head1|Tail], concatenate(Tail, List2, TempTail), List3 = [Head1|TempTail].
% See what we can generalise…
% Erm, already seems rather general!
%
% Looking at the code, we can simplify by:
%  1) making the first rule a fact (which I thought I might be able to do, but the wording implied I couldn't. And it worked so I left it)
%  2) shifting the unifying from the right to the left
%  3) taking advantage of "[Head|Tail]" matching an empty tail to combine the second two rules