%% From the end of lecture yesterday, here is the solution: /* [+,+,-] remove(Itm,L,L1): L1 = L, but L1 has one copy of Itm removed. (Note that Itm *must* occur in L, to satisfy this.) */ remove(Target, [Target|L1], L1). remove(Target, [F|L1], [F|L2]) :- remove(Target,L1,L2). %%%%%%%%%%%%%% % Sorting: % We'll just provide the 'spec' for sorting: % L2 is a sorted version of L1 if: % - L2 is in ascending order (er, non-decreasing). % - L1 is a permutation (re-arrangement) of L2, and scrapSort(L1,L2) :- permutation(L1,L2), nondecreasing(L2). % Here're the helper functions: % nondecreasing([]). nondecreasing([_]). nondecreasing([F,S|R]) :- F=Pivot, Biggers = [F|BiggerRest], partition(R,Pivot,Smallers,Equals,BiggerRest). /* N.B. You can remove the '=' terms from the above lines, reducing the code by 4 lines. Left in for clarity (?). */ % Note that we partition into *three* sections, % so that we always *reduce* the size of a partition % (even if our pivot is the maximum value). % Study the sol'n above, to see how the Prolog % makes sure we always recur on smaller lists (even % when the pivot is the maximum (or minimum) value. /* appendThree(L1,L2,L3,All) : All is the elements of L1 appended to L2 appended to L3. */ appendThree(L1,L2,L3,All) :- append(L1,L2,L1and2), append(L1and2,L3,All). /* The following is the same as the append/3 included with [basics]. */ append([],L2,L2). append([F|R],L2,[F|AllRest]) :- append(R,L2,AllRest).