Mercurial > repos > other > SevenLanguagesInSevenWeeks
view 3-Prolog/day2-concat.pl @ 68:b4f994693f7b
Fix condition check that was letting it backtrack to build a different set of rows
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sat, 07 Oct 2017 15:43:52 +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