znProjects Blog

Software is beautiful again!

Daily Coding Problem 5 - First-class Functions

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:

defcons(a,b):defpair(f):returnf(a,b)returnpair

Implement car and cdr.

Solution

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.

defcons(a,b):defpair(f):returnf(a,b)returnpair

Implementation of car

As the problem states, car needs to return the first element of the pair.

defcar(cns):# Returns the first parameter passed to the function.
deffst(x,y):returnxreturncns(fst)

Implementation of cdr

cdr needs to return the second element of the pair.

defcdr(cns):# Returns the second parameter passed to the function.
defsnd(x,y):returnyreturncns(snd)

Testing

We can perform some basic test to ensure that these implementation work correctly. Since the problem did not specify any test cases, i made some up using different types.