If I have the given dispatch-style function to represent a pair, how can I implement the same using a one-line lambda
function?
# ADT Level 0 (dispatch-style pair)
def make_pair(x, y):
"""Dispatch-style pair"""
def dispatch(m):
if m == 0:
return x
elif m == 1:
return y
return dispatch
You could do something like:
make_pair = lambda x,y: lambda m: x if m == 0 else y if m == 1 else None
The outer lambda returns an (inner) lambda waiting for an argument m
that returns the bound variables in the scope created by the outer.
>>>one_two = make_pair(1, 2)
>>>one_two(1)
2
>>> one_two(2)
>>>