-1

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Medvednic
  • 692
  • 3
  • 11
  • 28

2 Answers2

3

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)
>>> 
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
2

You can use imbricated lambdas to return a lambda expression:

>>> make_pair=lambda x,y:lambda m:x if m==0 else y
>>> a=make_pair(2,4)
>>> a(1)
4
>>> a(0)
2

lambda m:x if m==0 else y is (more or less) equivalent to your dispatch function (a(2) will return 4 in my case)

fredtantini
  • 15,966
  • 8
  • 49
  • 55