45 points · by homarp · 4y ago · 130 comments
Anyway I think Guido hates lambda because it feels like an appendage in Python, due to list comprehensions and due to expression-only bodies, restriction which was put in place probably because passing multi-line nameless functions as arguments is awkward in a whitespace-sensitive language/it just didn’t feel Pythonic to Guido to be passing large inline functions to functions.
My first thought exactly. Lisp is based on lambda calculus and it doesn't do automatic currying. Multiline lambdas require block delimiters more sophisticated than whitespace; hence they don't work in Python. It's no more complicated than that.
Languages which do that have issues representing very useful software engineering tools: optional arguments, variadic arguments and keyword arguments.
Currying is related to partial application; it refers to a technique for representing multivariate functions using only functions of one argument.
E.g. to obtain some f(x, y, z) we instead make it f(x)(y)(z), where f is a one-argument function applied to (x). That yields an anonymous one-argument function that is applied to (y), and that again yields a one-argument function applied to (z), which finally calculates f(x, y, z).
Whereas partial application is this: we already have a bona fide three-argument f(x, y, z), and the ability to call it with all three arguments at once. But for some reason, we call it as f(x)(y)(z). Now f needs 3 arguments but is called with just one, (x). So an anonymous two-argument function is produced which, if given two arguments will combine those with the one that was given and call f. Alas, that function is given only one argument, so it returns another one-argument function. When that one is given an argument, it all unwraps, and f ends up being called. These anonymous functions are understood to be produced because our notation is understood to have implicit partial application semantics. Under currying, things aren't implicit; f(x) is written as a one-argument function, which will have a lambda term in it. There is nothing to be implicit about in terms of application: all functions have one argument.
foo((lambda x, y:
for i in range(x):
y += i
return y),
20
) foo (lambda x, y::, 20) # :: means body of lambda follows
:: # optional, if there is only one lambda and line has no argument lines
for i in range (x):
y += i
return y
The lambda bodies immediately follow the line. If the line has arguments, those follow the lambdas: if foo(lambda x::, list) < bar(lambda y::, list):
:: # lambda x
return x + x
:: # lambda y
return 2 * y
return list # then statement of ifThis one is backwards: the benefit is forcing beginners to write well-formatted code. You would not believe the insane things people just learning can come up with, when in a C-style language where indentation doesn't matter.
For go, gofmt is so opinionated that you can't even configure it, which is kinda cool because it means all go code that uses it will look the same.
There's also rustfmt for rust and prettier for JS/TS (and I assume similar for lots of other languages I'm not familiar with), both of which are configurable, which I prefer - but I can see the upsides of a one-size-fits-all code formatting tool (especially for a language like go where a reasonably constrained feature set/syntax is an explicit goal of the language).
> datetime.date(2018, 3, 4)
> datetime.date(2018)(3)(4)
It's very obvious that the first of these date() function must be a function of three arguments (year, month, day) and the second, if the two calls are meant to return the same result, must be a function of one argument (year) that returns a function of one argument (month) that returns a function of one argument (day) that returns, presumably, a date.Syntactic sugar to call one date() as if it was the completely different other one would be recklessly dangerous. In particular, there are default parameters: date(1848) might legitimately mean something like 1/1/1848 (defaulting day and month to 1 and 1), not "give me a curried factory of dates in 1848".
Sure you can do that...
def add(a, b): return a + b
incr = lambda b: add(1, b) # like incr = l_add 1
incr(3) # ouputs 4
Is this whole article a complaint that Python isn't Haskell? What is the point? incr = partial(add, 1)
incr(3)Partial function application:
incr = partial(add, 1)
# or
def incr(x):
return add(x, 1)
z = incr(4)
(Side note: parent comment made a classic mistake, you shouldn't use a lambda if you're just going to assign it to a local variable, you should use a nested function definition.)Currying is function that returns a function:
def curried_add(x):
def inner(y):
return add(x, y)
return inner
z = curried_add(1)(4)I agree with your points, and with Izkata that the more relevant nuance is not that Python cannot curry, but that it doesn't do currying as fluently as Haskell, which I think was GP's point about the article. The crux of the article seems to have very little support for the argument of the title that lambdas shouldn't be in Python, but instead only seeks to make clear that "we do not use lambda with the intention of using lambda calculus." It's strongest contribution is to suggest that inline anonymous functions would be a helpful addition to the addition for Python to be able to do lambda calculus.
Python is a very poorly designed language, and when I would sometimes dig to find out why things here how they were, Guido was behind many of the decisions which I believe were bad.
I'm definitely not saying python is anywhere near perfect, and yes it certainly has design flaws (as does any complex system). But obviously it's done a lot of things right to gain the reach that it has.
Indeed it has. It is a very accessible (and even moreso "available") language.
But it has so many odd (and frankly wrong) peculiarities that big projects tend to become more difficult more quickly because of the mess that is most Python code. Some of the footguns are so rediculous that you cannot believe they exist; and even more astounding is the apologist arguments for why they should be the way they are. This one is my favorite: https://stackoverflow.com/questions/1132941/least-astonishme...
Since it is so accessible and has such a rich ecosystem, someone with little skill can cobble together a system which works well enough to get to production. But that junior developer pay rate cost (and ease of hiring) will mean that as the project matures and more and more features are added, the code more rapidly becomes incomprehensible. Everything being mutable, no types (except for bolted on, visually noisy, non-runtime linters), OOP missing some of the key information hiding features, awkward or half-baked functional features, and time/space performance problems all combine to make Python a terrible choice for non-prototype level projects.
That’s not a confusing language design. It’s a very simple case of mutability that new programmers stumble over because they don’t yet know how to reason about mutability.
But go ahead, tell us what should have been done instead here? Make it impossible to pass mutable arguments to functions? Or make it impossible to use mutable variables as default?
If you're going to throw around your words so sloppily like this at least give us a few decisions you don't like so we have something real to agree or disagree about, lol
See this thread if you want more than a few examples of how Python is poorly designed (as compared to Ruby): https://news.ycombinator.com/item?id=32116957
IMO the biggest issue is that they add features with absolutely no regard to how you could implement it with good performance. There are also a ton of features that let you do things that are just a really bad idea. Look at something like __subclasses__. Encourages terrible coding practices! (I learnt about it by reading some terrible code my colleagues wrote.) And good luck JITing that.
There's also a ton of syntax that is weird and asymmetric, like list comprehensions. Also the fact that you don't need to explicitly create variables is very error prone. Some of that is excusable given how old Python is but that doesn't mean it isn't bad.
Oh and import resolution. That's just downright terrible. No excuse there. I'd almost take #include over the insane mishmash of different ways imports work. It's even worse than JavaScript's module disaster.
Later ECMAScript editions have made good improvements, but there are still plenty of sharp edges and footguns in Javascript which simply do not need to exist.
Javascript is a leading language because _practically_ speaking (not strictly speaking) it is the only language you can use if you want to make things happen in the browser. And it came with every major web browser since the late 90s. THAT is why it gained immense marketshare.
Python has been included in Linux, *BSD, and macOS for years. It's a very simple language to make things happen with little effort; it is "accessible" to most people, particularly non computer scientists. It reads a little bit more like English than other languages, and it doesn't require compiling (again to accessibility).
All these things don't mean it's good. But it got picked up by non-developers and used to solve real world problems and a lot of research problems. More and more specialized modules were written for it, making it even easier to solve many problems.
So its accessibility and ecosystem have been good. But that doesn't mean it's good for building big, long lived, easily maintainable or extensible systems. It certainly doesn't mean it's good for building performant systems.
See elsewhere in this thread for my link to my biggest complaints (from an old discussion). I'm not a recognized expert on language design, but I've written significant quantities of production code in several languages, including Python, over many years.
No doubt people may disagree with my assertion, but using popularity as evidence of disagreement is not valid since popularity often does not correlate to the quality or suitability of something. History is full of companies, technologies, and practices where the most popular was absolutely not the best.
You can either implement a single function that handles the various types or you can add a method to each type, but the latter can be pretty tedious when you're implementing a bunch of functions / methods that operate on numerous types.
I ran into this when I started implementing map() for a few builtin types and found myself duplicating the loop-over-items code and started thinking, "Hmm, I wonder if this is why Python implemented len(), map(), etc as functions instead of methods."
Of course, you could implement an abstract class or equivalent for the generic aspects of len(), map(), etc, but then that gets pretty complex too.
So, based on that, which to reiterate is just a guess, I don't think the decision is bizarre at all. It's just an implementation tradeoff.
From a developer point of view, I slightly prefer method syntax for aesthetic reasons, but practically speaking it doesn't make any difference whether I type obj.len() or len(obj), and IMO neither is more or less object-oriented than the other (which is a common complaint about len() et al).
There is a method on all objects which are a collection:
__len__()
You can try it out yourself. x = [1,2,3,4]
print(x.__len__()) #4
y = "abcdefg"
print(y.__len__()) #7
z = { "a": "b", "c": "d"}
print(z.__len__()) #2
len() is just syntactic sugar for calling __len__(). The "dunder" methods in python are a standard way of extending classes.It is generally considered bad practice to call dunders, with the idea being that those are more private or more internal methods which you should not directly depend on (unless you're willing to accept more breaking changes). Instead, you depend on other more intentionally public methods which themselves may call dunders or do other things.
I think the issue the parent was really focusing on was the fact that many methods are instance methods, but there are some global functions.
Python suffers from being sort of OO, sort of procedural, and even less but also sort of functional.
It's a bit like a flying camper van. It's a weird plane with tricky controls, poor fuel economy, cramping sleeping areas, and a bump ride on roads. But boy does it have a lot of mods and attachments, so you can do just about anything with it using only a pair of plyers and a flathead screwdriver. Thus, it attracts beginner mechanics and enthusiasts who build monstrosities that experienced mechanics have nightmares about but which pointy haired bosses don't understand and think the feature set is great.
len() makes no sense for numbers, booleans, None, and probably other types I cannot think of at the moment.
Python has a LONG list of built in functions, most of which are only applicable to a few types of parameters. They could just as well be object methods.
https://docs.python.org/3/library/functions.html
Some of those methods, like sorted(), are terrible names. A past tense verb name... so instead of telling Python, "Hey, please sort() this", you say "Please give me a sorted() thing".
So you have the collection.sort() method or the built in sorted() method. They both sort, but they have different options; and significantly, sort() mutates the collection, whereas sorted() returns a new collection.
This is inconsistent and creates unnecessary cognitive load. It's another example of a Frankenstein language.
https://docs.hylang.org/en/stable/api.html#fn
Still no currying, though. But an anonymous function can be `fn` instead of `lambda`.
According to this blog post there isn't, and yet there is? I'm more confused by the way this was written than Python's implementation of the "lambda" keyword.
λx.λy.λz. x (y z)
If you wrote the much more user friendly λ x y z . x (y z)
And tried currying it then it would fail.The author is complaining that Python doesn't use a dialect of lambda functions used in Haskell. Which is true. Python isn't Haskell and shouldn't be.
lambda: sub($x) {$x+1} decl sub{shift+1}(args) call
or ruby-like: {shift+1}->list
https://sarabander.github.io/sicp/html/1_002e3.xhtml#g_t1_00...
Honestly it's likely that for most of the history of the term it's been more used for "incorrect" meanings than "correct" ones.
He makes a big point about currying in his particular manner, but what's wrong with
f = lambda x,y: x+y
g = lambda y: f(3,y)
That's also currying right? I've always been a little confused as to why the style he advocates is necessarily better. I'm not a functional guy so I'm maybe I'm missing something, what is the benefit of syntactic sugar for partial application to the first (or last) argument of a function? What if I want partial application of a function with the middle argument specified? Now you're out of luck and have to do the above anyway.ETA: on the main point
> In Python, we do not use lambda with the intention of using lambda calculus. Our syntax needs to encode our intention in the places we have used it, and where we will use it. These use cases are inline, anonymous functions.
That seems needlessly nitpicking. Wikipedia has "lambda function" as a synonym for anonymous function so it seems pretty widespread in our language at this point. https://en.wikipedia.org/wiki/Anonymous_function
> g = f(3) # no second parameter provided
g = <unary function> # however it would be indicated in the python shell
To get it in Python you'd need to do this: f = lambda x: lambda y: x + y
g = f(3) # result is a function, or funcallable, or whatever Python calls the resultant type
This makes the currying explicit. In general, currying is taking an n-ary function and reducing it to a series of n unary functions. These three are equivalent, in Haskell(ish, rusty): f x y = x + y
g x = \y -> x + y
h = \x -> \y -> x + y
In Haskell, you don't have to use the explicit form of `h` (or the explicit form in the Python example) if you don't want to (and it would probably be weird if you used it extensively).> To get it in Python you'd need to do this:
> f = lambda x: lambda y: x + y
> This makes the currying explicit. In general, currying is taking an n-ary function and reducing it to a series of n unary functions.
Something's gone wrong; your example of explicit currying conflicts with your definition of currying. `f` is a unary function.
f = lambda x, y: x + y
My updated curried `f` is a unary function, but it returns a unary function itself: f = lambda x: lambda y: x + y
That's what currying is. I just reused the name, if you prefer: curried_f = lambda x: lambda y: x + y
EDIT:And note, it makes the partial application less explicit/verbose than the original, but the currying is very explicit because of Python's syntax.
g = curried_f(3)
Is "just" a function call, while: g = lambda y: f(3, x)
does the same thing (functionally, at least) but the partial application is made explicit.No, currying is the transformation that takes a function f such that f(x0, x1, ... xn) = r and returns a function f' such that f'(x0)(x1)... (xn) = r.
Haskell doesn’t really have currying so much as having only one argument functions and a syntax for defining them that means one way to define a function that works like the result of currying a multiargument function looks a lot like defining a multiargument function in other languages.
The lambda keyword is long which makes it a pain, but currying really is equivalent to specialised partial application right? People seem to love currying so much I feel like I don't understand something here.
For context I work a lot with java, R, and Python which all have anonymous functions and higher order functions, but are all decidedly _not_ "functional languages".
It does, it just doesn’t support statements (not even one) in lambdas, since a lambda (however many lines it takes up) contains a single expression.
Defining a function inline with no name?
Also though, I kind of feel like currying/partial application is one of the most overhyped feature of all time. With lexical scoping and closures, the number of times I've needed it is: never. Admittedly I'm not using lisp or haskell every day, but I feel like most of the greatest features of those languages have been generally stolen where possible, and yet currying always seems like an afterthought.
mult_10 = partial(mult, 10)
mult_10_20 = partial(mult_10, 20)
print(mult_10_20(30))
The only context I can think of off the top of my head where currying might be useful is binding a "this" or "self" object, but, if I'm using a class I already get that. Maybe you could use it to pass through some set of context objects, but then, you could already do that by just creating a data structure to hold those objects.The Lambda Calculus really is formally about single argument functions. Here is one of many good references for that: https://plato.stanford.edu/entries/lambda-calculus/
Hence, the multi-argument lambdas of Python are something of a contradiction in terms, or a kind of artistic license. Now that I think about it, I can't think of a good reason not to use `def` for the anonymous function syntax in Python:
def (x, y, z...): <expr>It needn't be: https://personal.utdallas.edu/~gupta/courses/apl/lambda.pdf
Currying is just an easy way to deal with multi-argument functions. You then need to add a bunch of syntactic sugar to avoid the issues the the author complains about here (something that Haskell has done). You could just as easily go the opposite route and add a bunch of different syntactic sugar and deal with multi-variable functions directly (as python does).
But I agree that there should be no lambdas in Python-- but just Python -- because Python's enforced indendentation syntax rules are so hostile to those multi-statement lambdas and closures which are absolutely trivial in a language like Lisp. The hobbled lambdas that remain are, well, basically gunk for currying.
When's the last time you used Java? I remember having to use anonymous classes but we've had lambdas for a good 8 years now? Or is it that you don't like how lambdas "fullfil" a SAM interface instead of having a true Function representation.
If it's the latter, I'm sincerely very curious what we're missing out on since I'm mostly used to it.
It's funny how Java developers perceive "lambdas" as (param, param) -> { code } blocks to be used in consumers and iterators etc. This is a weird mutation of the general concept due to Java's lack of functions: as a Lisp developer I don't perceive lambda expressions like that at all. The use of lambda expressions is much more general than this: it's simply the creation of function pointers for many tasks. For me, nearly 100% of the time it's to create them to be stashed away as callbacks. And in Java, the only realistic way to do this still is with anonymous classes.
'etymology/provenance' is not inline with current use; hence don't use.
rather silly tbh. you'd have to stop using most words in english (let alone entire systems plagiarized from other cultures) if you take such a stance.
as for the debate, actually, one could argue python would benefit greatly by going the other direction: make multi-line definitions of lambda possible (ala all the lisps).
In JavaScript I constantly use anonymous functions everywhere and they are easy to understand and use.
The same concept in Python is clunky, hard to understand and definitely not easy to use.
JavaScript absolutely trounces Python when it comes to compact, minimal, highly expressive anonymous functions.
JavaScripts arrow functions are so elegant and so compact and so effective that they completely change the way I program JavaScript. No such equivalent exists in Python.