Added #dcp 567 - implementing cons/car/cdr.

This commit is contained in:
2026-05-27 21:23:44 -07:00
parent ef3b7511e8
commit 123f880c86

31
problems/cons_car_cdr.py Normal file
View File

@@ -0,0 +1,31 @@
"""
cons(a, b) constructs a pair, and car(pair) and cdr(pair) return the first
and last element of that pair.
car(cons(3, 4)) == 3
cdr(cons(3, 4)) == 4
Given this implementation of cons, implement car and cdr.
"""
def cons(a, b):
return lambda f: f(a, b)
def car(pair):
return pair(lambda a, b: a)
def cdr(pair):
return pair(lambda a, b: b)
# --- tests ---
assert car(cons(3, 4)) == 3
assert cdr(cons(3, 4)) == 4
assert car(cons("a", "b")) == "a"
assert cdr(cons("a", "b")) == "b"
print("All tests passed!")