Problem

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

Code

Python

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

def cdr(pair):
    return pair(lambda a, b: b)
 
# Test the functions
print(car(cons(3, 4)))  # Output: 3
print(cdr(cons(3, 4)))  # Output: 4

Java

import java.util.function.BiFunction;

interface Pair {<T > T apply(BiFunction < Integer, Integer, T> func);
}


public class Solution {

	public static Pair cons(int a, int b) {
		return func -> func.apply(a, b);
	}

	public static int car(Pair pair) {
		return pair.apply((a, b) -> a);
	}

	public static int cdr(Pair pair) {
		return pair.apply((a, b) -> b);
	}

	// Test the methods
	public static void main(String[] args) {
		System.out.println(car(cons(3, 4))); // Output: 3
		System.out.println(cdr(cons(3, 4))); // Output: 4
	}
}