Hacker News new | ask | show | jobs
by saghm 2212 days ago
I agree with you that having more than a single expression in lambdas would be super nice. That being said, I don't think it's necessarily stateful to allow more than a single expression! If you don't reassign any variables, then it's equivalent to a single expression. For instance, something like this (using made up syntax for extended lambdas) isn't stateful:

    lambda i:
        square = i * i

        if i < 0:
            return -1 * square
        else:
            return square
A decent heuristic for whether an algorithm is stateful might be to check if you can map it pretty easily to something like Haskell. In this case, it's not hard to do at all:

    \i ->
        let square  = i * i in
        if x < 0 then -1 * x else x
Of course, it might be more natural for some programmers to write the Python code in a stateful way like this:

    lambda i:
        square = i * i

        if i < 0:
            square *= -1

        return square
2 comments

I'm sure there are cases where multiple lines would be nice, but I don't think this is one. This seems easier to read to me:

    lambda i: -i * i if i < 0 else i * i
Also, the functional way of doing multiple lines in a lot of situations would typically be to compose smaller lambdas.
Yeah, this is a trivial example. I picked it specifically to show that multi-line lambdas don't have to be stateful, not as an example of a lambda that couldn't be written in one line.
And there is math.copysign
very quick reply, and I've done this in other langs that allow procedures-done-as-lambdas, create your own control flow mechanisms with 'reasonable' syntax, something like

  with_file("c:/blah/data.csv", lambda fl:
    # do stuff with file variable fl
    # other statements
    # ...
  )
The file is opened, the block of code of the lambda does its thing, the file is closed at the end, exception-safe.

Python can do this another way (with 'with' objects or something, and it's quite clean and neat, but that's quite recent IIRC), this simpler IMO. Have used this, it's called the loan pattern, in scala, vb.net and C#, and prob others.

The arbitrary restriction on lambdas blocks composability, which disallows useful tricks like this.