changeset 60:643eec1f9e3a

Add a custom implementation of append/3
author IBBoard <dev@ibboard.co.uk>
date Wed, 27 Sep 2017 20:48:28 +0100
parents f86bb0d669be
children 49cb2f7af872
files 3-Prolog/day2-concat.pl
diffstat 1 files changed, 22 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/3-Prolog/day2-concat.pl	Wed Sep 27 20:48:28 2017 +0100
@@ -0,0 +1,22 @@
+% 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
\ No newline at end of file