Daily Coding Problem – cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.

Daily Coding Problem sends daily coding problem sample when you subscribe to their service. This service is very useful to practice your coding ability and think through the logic you will be using to solve the problem.

Table of Contents

Problem

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.

Context

So what is car and cdr anyway? You can check out some more details about car and cdr in Wikipedia.

A cons cell is composed of two pointers; the car operation extracts the first pointer, and the cdr operation extracts the second.

Solution

For the solution for this problem, I reference the code from this github.

Code Example

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

def car(cons):
    return cons(lambda a, b: a)

def cdr(cons):
    return cons(lambda a, b: b)

print(car(cons(3, 4)))
print(cdr(cons(3, 4)))

Feel free to share this post!

Scroll to Top