Hacker News new | past | comments | ask | show | jobs | submit login

I really don't understand this obsession with anonymous functions. If you're doing anything longer than one line, there is absolutely no reason why you should be sticking the entire function definition as a parameter.

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.




I suggest you read SICP and gain an appreciation for higher-order functions. Once you do, you will probably have answered your own question. http://mitpress.mit.edu/sicp/


Doesn't that section use lambda for anonymous functions? http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html...

The OP is complaining about lambda functions in Python.


In python, it would be proper to say that ALL functions are lambdas except that some/most of those lambdas are assigned to variables via syntactic sugar (this is made very plain in sicp which is the main reason for suggesting it).The only thing different about python vs most other languages is guido refusing to implement multi-line lambdas.

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) ]


"In python, it would be proper to say that ALL functions are lambdas except that some/most of those lambdas are assigned to variables via syntactic sugar"

If a function is "assigned to a variable" then it's no longer a lambda, because it's bound to an identifier. But I suppose the lines are a tad blurred.


While I agree that the function "has a name", the function is still anonymous in the sense that pointers don't have types, only values have types. As a side effect of converting church's model to Turing's model, all "unnamed" lambda functions are given one-time symbols as are all anonymous numbers, arrays, classes, objects, etc.

  x = lambda x: x+x #a lambda, but has a named pointer
  x = 5
lambda is still in memory (until garbage collection), but it no longer has a pointer to it.

  def x(y):
    return y+y
  
  x = 5 #the "named" function above is now without a pointer
A little off-topic (but answers your previous question and perhaps looks a little deeper into lambdas), but let's take a quick look at javascript. JS developers use lambda functions both because lexical closures don't pollute the global namespace, they offer modules and alternatives to prototypal objects, and because the language tends to make heavy use of callbacks (which demonstrate the bad side of lambda functions). JS also only makes subtle differences between lambdas and named functions.

  //lambda expression
  var x = function (){};

  //named function
  function x() {}

  //named lambda expression
  var x = function x() {};

  //self-executing lambda (returns 5)
  (function (x) {return x;}(5));
note that this would be a self-executing lambda in python

  (lambda x: x)(5)
basic module pattern using self-executing lambda

  my_module = (function (self) {
    "use strict"
    self = self || {};

    //private
    //pretty much inaccessible to the outside scope
    var privateVar = 5;
    //lambda expression again
    var privateFunc = function () {};

    //public
    self.publicVar = 5;
    self.publicFunc = function () {};
    self.getPrivateVar = function () {
      return privateVar;
    };

    return self;
  }(my_module));

  my_module.publicVar = 8;
  my_module.publicFunc();
  my_module.getPrivateVar();
This is where too many lambdas becomes a problem. Judicious use of naming (even though they're only used once) makes things more legible.

  func1(function () {
    func2(function () {
      func3(function () {
        func4(function () {
      })
    })
  })


Thanks for the link to the relevant chapter!


Why would zo1 want to read SICP? zo1 is clearly quite happy with Python's named functions, and has no immediate incentive to "read SICP and gain an appreciation for higher-order functions."


I either assume that the parent poster was serious about the question or rhetorical. Given the apparent lack of knowledge, I assume the question was serious. If the question was serious, does it not deserve a serious response?

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.


Indeed, you are right. I was quite curious about them, and I wanted to know if there was something I was missing. Some reasoning that I knew not of, and that others did.

However, I'm about halfway through the chapter on "Higher order procedures" in the book you linked to, and have skimmed the rest of that chapter. And I've yet to find a valid pro for anonymous methods. Nothing I've found so far as to the benefit of using anonymous functions.

It does however, continuously reiterate the benefit of being able to pass "procedures as arguments" and to be able to return them from normal functions. So far, that's been the only "pro" and it's one that's solved by function pointers or having functions as objects, and not by anonymous methods. I'm still open for convincing, genuinely.

Here's another jewel from that chapter: "The resulting procedure is just as much a procedure as one that is created using define. The only difference is that it has not been associated with any name in the environment."

On a side note, your initial post was a tad condescending. The other post at least gave me the relevant chapter, instead of saying "here, read this for yourself". The least you could have done was give me a few short points why you think anonymous methods are superior in some way. Perhaps pointing me to a large blob of text was your way of deferring your own justifications for their use by not having to explain it to me (and as a consequence, yourself)?


My apologies. I was somewhat sleep deprived at the time and it sounded a lot better in my head.

SICP's point with higher-order functions is that code is data and that functions are no different than numbers or lists or whatever. In the function below, I've named everything.

  def add4Mul2(x):
    z = 4
    y = 2
    return (x + y) * z

  lst = [1,2,3,4]
  x = map(add4Mul2, lst)
the short version without any variable names.

  x = map(lambda x: (x+2)*4, [1,2,3,4])
I don't name the function for the same reason that I don't name the 2, the 4 or the array -- I don't need to because I use them one time. If I were using (x+2)*4 all the time, then I'd give it a name, but since I only use it once, it's less of a problem to treat the function like any other constant data -- use the data without assigning it to a variable first.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: