title: Prolog - return second to last list element
body: <p>puzzling over a problem of trying to return the second to last element in a list written in Prolog.  This language is interesting to use but I'm having trouble getting my head wrapped around it. Here is what I have:</p>
  
  <pre><code>secondLast([X], X).
  secondLast(X, [Y], X) :- secondLast(Y, K).    
  secondLast(X, [Y|Z], K) :- secondLast(Y, Z, K).   
  secondLast([X|Z], Ans) :- secondLast(X, Z, Ans).
  </code></pre>
  
  <p>so calling <code>secondLast([a, b, c, d], X).</code>
  <code>X</code> should equal <code>c</code>.</p>
  
  <p>Any ideas?</p>
  
  <p>Thanks!</p>