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.

Solution

I wrote the solution in Swift. Feel free to comment with your solution in the language of your choice.

Let’s first convert the function cons(a, b) from Python into Swift. I turned it into a generic function for fun. Now it can be used for more than just integers.

``````func cons(_ a :T,_ b :T) -> () -> (T, T) {
func pair() -> (T, T) {
return (a, b)
}
return pair}``````

And now for my solution.

``````func car(_ cons :() -> (T, T)) -> T {
let firstElement: T = cons().0
return firstElement
}

func cdr(_ cons :() -> (T, T)) -> T {
let lastElement: T = cons().1
return lastElement
}
``````

Let’s test it.

``````print("Left element: \(car(cons(3,4))); Right element: \(cdr(cons(3,4)))")
print("Left element: \(car(cons("a","b"))); Right element: \(cdr(cons("a","b")))")``````

Left element: 3; Right element: 4
Left element: a; Right element: b

It works!

This problem was provided by Daily Coding Problem. Get exceptionally good at coding interviews by solving one problem every day.

David Inga

Designed by David Inga in California.