Software is beautiful again!

This problem was asked by Jane Street.

`cons(a, b)`

constructs a pair, and `car(pair)`

and `cdr(pair)`

returns the first and last element of that pair. For example, `car(cons(3, 4))`

returns `3`

, and `cdr(cons(3, 4))`

returns `4`

.

Given this implementation of cons:

```
def cons(a, b):
def pair(f):
return f(a, b)
return pair
```

Implement `car`

and `cdr`

.

This is not a difficult problem, but requires that the person understand how to use functions as first-class members of the language. Admittedly, python is not a language I use often. I personally prefer statically typed languages and the compile-time goodness that comes along with them.

Regardless, the solution is quite simple. The key is that `cons`

returns a function that expects a function as an argument. That argument is what must, in turn, return the correct value from the pair.

First, let's put the `cons`

function into scope.

In [1]:

```
def cons(a, b):
def pair(f):
return f(a, b)
return pair
```

In [2]:

```
def car(cns):
# Returns the first parameter passed to the function.
def fst(x, y):
return x
return cns(fst)
```

In [3]:

```
def cdr(cns):
# Returns the second parameter passed to the function.
def snd(x, y):
return y
return cns(snd)
```

In [4]:

```
a = cons(1, 2)
b = cons('a', 'b')
c = cons(5.0, 6.0)
d = cons(True, False)
```

In [5]:

```
print ('a: ', car(a), ',', cdr(a))
print ('b: ', car(b), ',', cdr(b))
print ('c: ', car(c), ',', cdr(c))
print ('d: ', car(d), ',', cdr(d))
```