0

I want to return a comparison function from a lambda function and use it depending on the type of the input. Is there a way to do it?

def p12(p):
    f = lambda p: compare_nr if type(p) == int else compare_str
    return f
if __name__ == '__main__':
    cmp1 = p12(0)
    cmp1(2,3)
    cmp2 = p12('')
    cmp2('Mississippi','fall')
10
  • 1
    Yeah sure, what isn't working? As an aside a lambda shouldn't be used if you are going to name it anyway... it defeats the entire purpose of an anonymous function. Commented Mar 25, 2017 at 23:54
  • 3
    yeah just remove lambda. Commented Mar 25, 2017 at 23:56
  • 1
    What do you mean you aren't allowed??? Commented Mar 25, 2017 at 23:58
  • 3
    Asking someone to complete the challenge for you defeats the entire purpose. Commented Mar 26, 2017 at 0:00
  • 1
    If you're a novice, your first resource should be books and tutorials, not posting a new question. Commented Mar 26, 2017 at 0:02

3 Answers 3

1

There is a way to do it (in Python 3) without using a lambda: functools.singledispatch. With this, you can create a single-dispatch generic function:

A form of generic function dispatch where the implementation is chosen based on the type of a single argument.

[Emphasis mine]

It adds overloaded implementations to the function which are called depending on the type of the first argument, and fortunately, your p12 function takes only one argument.

from functools import singledispatch

@singledispatch
def p12(p):
     ...

@p12.register(int)
def _(p):
     '''compare integers'''
     ...

@p12.register(str)
def _(p):
     '''compare strings'''
     ...

p12(0) # calls integer dispatch
p12('') # calls string dispatch

And you can still add more candidate functions for other Python types to overload p12.

Sign up to request clarification or add additional context in comments.

Comments

0

The problem encountered was that I returned the actual lambda function instead of the defined one.

def p12(p):
    f = lambda p: compare_nr if type(p) == int else compare_str

    #here was the problem
    #return f
    return f(p)
if __name__ == '__main__':
    cmp1 = p12(0)
    cmp1(2,3)
    cmp2 = p12('')
    cmp2('Mississippi','fall')

Comments

0

You could alternatively replace lambda with a higher order function and do the same.

def p12(p):
    if type(p) == int :
        return compare_nr
    else:
        return compare_str

if __name__ == '__main__':
    cmp1 = p12(0)
    cmp1(2,3)
    cmp2 = p12('')
    cmp2('Mississippi','fall')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.