by garindra · 12y ago · 0 comments
Python, on the other hand, is definitely one of the worst at this. You can only create one-line, single-expression anonymous function with its lambda keyword. Of all the languages you want to convert to JS so that it runs on the browser, Python is probably the last.
I've had great usage from Javascript where I have separate functions with proper names and formatting, and then pass a reference to them into the code that asks for them.
Can someone please enlighten me about this whole anonymous functions thing that Javascript seems to have popularized? What are some of the pro's of using it over regular named/defined functions that sit by themselves and are reusable.
The OP is complaining about lambda functions in Python.
As to any complaint, lambdas exist in python (that is, are made accessible to the programmer) for the exact reason python also has a for loop in addition to a while loop -- because they make things easier and more maintainable.
def myApplyAdd(func, x):
return lambda y: func(x+y)
applyAddInst = myApplyAdd(lambda z: z*2, 20)
applyAddInst(3) #output 26
becomes much less maintainable without lambdas and pollutes the scope with unnecessary variables you must then keep track of def myApplyAdd(func, x):
def innerAdd (y):
return func(x + y)
return innerAdd
def mulByTwo(x):
return x*2
applyAddInstance = myApplyAdd(mulByTwo, 20)
applyAddInst(3) #output 26
I would also note that list comprehensions make heavy use of lambdas. For example, the following is actually using a for loop and calling lambda i: i**2
each each iteration result = [ i**2 for i in range(3, 30) ]Faced with squeezing an explanation into a limited post or recommending one of the best books on computer science (written by teachers with many years experience in teaching these self-same principles), should I not recommend the book that will allow the poster to expand his/her horizons?
The poster was sufficiently motivated to ask the question. I was willing to post what I believed at the time to be the best answer to the question. If the poster's desire to know is sufficient, then he/she will take the time to explore the suggestion. If not, then things will stay as they are. In either case, my only interaction is my choice to share a suggestion or remain silent.