Compare commits

...

2 Commits

Author SHA1 Message Date
5e655f67f3 Add System Design Interview book. 2026-05-27 21:23:58 -07:00
123f880c86 Added #dcp 567 - implementing cons/car/cdr. 2026-05-27 21:23:44 -07:00
2 changed files with 31 additions and 0 deletions

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!")

Binary file not shown.