32 lines
540 B
Python
32 lines
540 B
Python
"""
|
|
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!")
|