title: Swapping binary trees in prolog
body: <p>This is exercise 3.5 from <em>Learn Prolog Now</em>. They put it before explaining lists so I need a procedure that doesn't involve lists.</p>
  
  <p>The task is to swap the leaves of nested binary trees. If the query is </p>
  
  <pre><code>swap(tree(tree(leaf(1), leaf(2)), leaf(4)), T).
  </code></pre>
  
  <p>the answer should be </p>
  
  <pre><code>T = (tree(leaf(4), tree(leaf(2), leaf(1))).
  </code></pre>
  
  <p>With </p>
  
  <pre><code>swap((X, Y), (Y, X)).
  
  swap(tree(X, Y), T) :- 
     swap((X, Y), (Y, X)), 
     T = (Y, X).
  </code></pre>
  
  <p>I get</p>
  
  <pre><code>T = (leaf(4), tree(leaf(1), leaf(2))).
  </code></pre>
  
  <p>As you see the <code>leaf(1)</code> and <code>leaf(2)</code> didn't get swapped. I want some hints or even your procedure and it should work with any depth of the nodes. Thanks. </p>