<div class="notebook"> <div class="nb-cell markdown" name="md2"> # This is a notebook about different ways to append a list to another list in prolog. We will use the following two lists [1,2,3,4,5] and [a,b,c,d,e] Some of the solutions can do more than just append 2 lists. Only their ability to append 2 lists are compared here. __Press play on the queries and look at the # of inferences.__ _You can find me on twitter @modulovalue_ Discussion on Reddit: https://www.reddit.com/r/prolog/comments/l2ocnb/i_made_a_tiny_comparison_of_different_ways_to/ </div> <div class="nb-cell markdown" name="md1"> --- --- ## Using append </div> <div class="nb-cell query" name="q1"> time(append([1,2,3,4,5], [a,b,c,d,e], X)) </div> <div class="nb-cell markdown" name="md6"> --- --- ## Using a custom append </div> <div class="nb-cell program" name="p4"> cappend([], RESULT2, RESULT2). cappend([H|T], LIST, [H|RESULT]) :- cappend(T, LIST, RESULT). </div> <div class="nb-cell query" name="q7"> time(cappend([1,2,3,4,5], [a,b,c,d,e], OUT)) </div> <div class="nb-cell markdown" name="md3"> --- --- ## list//1 from https://www.metalevel.at/prolog/dcg </div> <div class="nb-cell program" name="p1"> list2([]) --> []. list2([L|Ls]) --> [L], list2(Ls). concatenation([]) --> []. concatenation([List|Lists]) --> list2(List), concatenation(Lists). </div> <div class="nb-cell query" name="q2"> time(phrase((list2([1,2,3,4,5]), list2([a,b,c,d,e])), Ls)) </div> <div class="nb-cell query" name="q4"> time(phrase(([1,2,3,4,5], [a,b,c,d,e]), Ls)) </div> <div class="nb-cell query" name="q6"> time(phrase(concatenation([[1,2,3,4,5],[a,b,c,d,e]]), Ls)) </div> <div class="nb-cell markdown" name="md4"> --- --- ## Using list differences </div> <div class="nb-cell program" name="p2"> dappend(d(A, C), d(C, D), d(A, D)). </div> <div class="nb-cell query" name="q3"> time(dappend(d([1,2,3,4,5|X], X), d([a,b,c,d,e|Y], Y), Z)) </div> <div class="nb-cell markdown" name="md5"> To get the final list you just have to finalize it with an empty list </div> <div class="nb-cell query" name="q5"> time(dappend(d([1,2,3,4,5|X], X), d([a,b,c,d,e|Y], Y), d(LIST, []))) </div> <div class="nb-cell markdown" name="md7"> </div> <div class="nb-cell markdown" name="md8"> # Bonus </div> <div class="nb-cell markdown" name="md9"> How to create a difference list from scratch with append. _You should prefer passing around difference lists and not creating them from scratch because that takes linear time with respect to the length of the list._ </div> <div class="nb-cell query" name="q8"> L1 = [1, 2, 3], time(append(L1, TAIL, X)), DIFFERENCELIST = X-TAIL. </div> </div>