title: Prolog - Add element to List in a recursive predicate
body: <p>I need to build a Prolog predicate which returns in Books2009 a list of books that were published in the year of 2009, and in Books2014, the books published in 2014.  </p>
  
  <p><strong>setbooks</strong>: will only be used to "create" the list of books that will be used in the predicate booksList_2009_2014.<br>
  <strong>booksList_2009_2014(L, Books2009, Books2014)</strong>: this is the predicate we are trying to create and run ("L" is a list of books previously set in <em>setbooks</em>).  </p>
  
  <p><strong>My code explanation</strong>: I tried to make the predicate <em>insertAtEnd</em>(which would be used later, inside <em>booksList_2009_2014</em>) that will insert an element in the end of a list.<br>
  Then I wrote the predicate <em>booksList_2009_2014</em> for the simplest case (recieving an empty list of books), then for recieving a list of books with 1 element only, and then, a recursive case that would do the job for a list of books no matter how long it is.</p>
  
  <p><strong>This is my code file:</strong></p>
  
  <pre><code>setbooks([book('Name 5', 'Publisher ABC', date(12, 2014)), book('Name 4', 'Publisher ABC', date(05, 2009)), book('Name 3', 'Publisher ABC', date(02, 2009)), book('Name 6', 'Publisher ABC', date(03, 2013)), book('Name 2', 'Publisher ABC', date(12, 2014)), book('Name 1', 'Publisher ABC', date(06, 2009))]).
  
  insertAtEnd(X,[ ],[X]).
  insertAtEnd(X,[H|T],[H|Z]) :- insertAtEnd(X,T,Z).
  
  booksList_2009_2014([],_,_).
  
  booksList_2009_2014([book(Name,Publisher,date(M1,Y1))],Books2009, Books2014):-
      Y1=2014 -&gt; insertAtEnd(book(Name,Publisher,date(M1,Y1)),_,Books2014);
      Y1=2009 -&gt; insertAtEnd(book(Name,Publisher,date(M1,Y1)),_,Books2009).
  
  booksList_2009_2014([H|T],Books2009, Books2014):-
      booksList_2009_2014(T,Books2009, Books2014).  
  </code></pre>
  
  <p>Im not sure, but I think the code isnt correct somewhere in the recursive code: </p>
  
  <pre><code>booksList_2009_2014([H|T],Books2009, Books2014):-
          booksList_2009_2014(T,Books2009, Books2014).  
  </code></pre>
  
  <p>When I type <strong>setbooks(L),booksList_2009_2014(L,Books2009, Books2014)</strong>, the program is returning me just the last book of the list.. For example:  </p>
  
  <pre><code>Books2009 = [book('Name 1', 'Publisher ABC', date(06, 2009))] 
  </code></pre>
  
  <p>Can someone help me? Pleeeasse???</p>