## ---------------------------------------------------------------- ## an implementation of the PAIR interface using Python lists ## ---------------------------------------------------------------- def list_make_pair(a, b): return [a, b] def list_first(pair): return pair[0] def list_second(pair): return pair[1] ## ---------------------------------------------------------------- ## an implementation of the pair interface using Python functions ## ---------------------------------------------------------------- def proc_make_pair(a, b): return lambda p: p(a, b) def proc_first(pair): return pair(lambda a, b: a) def proc_second(pair): return pair(lambda a, b: b) ## ---------------------------------------------------------------- ## run a simple test to demonstrate the different implementations ## ---------------------------------------------------------------- def do_some_pairs(type_str, MAKE_PAIR, FIRST, SECOND): print('Using the', type_str, 'implementation of the pair interface') pair_1 = MAKE_PAIR(2, 3) pair_2 = MAKE_PAIR(1, pair_1) x = FIRST(pair_2) y = FIRST(SECOND(pair_2)) z = SECOND(SECOND(pair_2)) print(x, y, z) do_some_pairs("list", list_make_pair, list_first, list_second) do_some_pairs("function", proc_make_pair, proc_first, proc_second) ## ---------------------------------------------------------------- ## We could also implement pairs using Python tuples, dictionaries, ## functions + booleans, functions + symbols, and ... ## ----------------------------------------------------------------