title: Python: functional programming with cons, car & cdr
body: <p>There is this problem that goes like this:</p>
  <blockquote>
  <p><code>cons(a, b)</code> constructs a pair, and <code>car(pair)</code> and <code>cdr(pair)</code> returns the
  first and last element of that pair. For example, <code>car(cons(3, 4))</code>
  returns <code>3</code>, and <code>cdr(cons(3, 4))</code> returns <code>4</code>.</p>
  </blockquote>
  <p>Now, I have seen the solution, but I'm wondering if anybody can explain how to actually <em>think</em> to reach the solution?</p>
  <ol>
  <li><code>cdr(cons(3, 4))</code>: in what order are these two functions evaluated? I would normally think that <code>cons(3, 4)</code> are evaluated first, but that does not make sense in this case, because <code>cons(3, 4)</code> returns a function where arguments 3 and 4 are &quot;integrated&quot;, so there is no way of singling out the arguments.</li>
  <li>It seems to me that <code>car(f)</code> returns a function, so how can <code>cons(3, 4)</code> return <code>3</code>?
  <strong>EDIT</strong>: typo, should be <code>car(cons(3, 4))</code> instead of <code>cons(3, 4)</code></li>
  <li>I am obviously trying to solve this problem because I want to learn Python, but would you recommend me to skip these problems? I am tempted to do so by reading here: <a href="https://stackoverflow.com/questions/1892324/why-program-functionally-in-python">Why program functionally in Python?</a></li>
  </ol>
  <p>Solution:</p>
  <pre><code>def cons(a, b):
      def pair(f):
          return f(a, b)
      return pair
  
  def car(f):
      def pair(a,b):
          return a
      return f(pair)
  
  def cdr(f):
      def pair(a, b):
          return b
      return f(pair)
  
  print(car(cons(3,4)))
  Output: 3
  print(cdr(cons(3,4)))
  Output: 4
  </code></pre>