adamsol / Pyxell

Multi-paradigm programming language compiled to C++, written in Python.
MIT License
54 stars 6 forks source link

Lambda functions #7

Closed sirex closed 3 years ago

sirex commented 3 years ago

I think, in Python lambda functions looks ugly, by design, in order to discourage use of lambdas if possible (I might be wrong).

Consider lambdas similar to ones used by Julia, for example, this Pyxel code:

double = lambda x: x * 2

Could look like this:

double(x) = x * 2

Or:

double(x: Rat): Rat = x * 2

Multi statement lambdas, could look like this:

count(n) def
    for i in n..0 by -1 do
        print i
adamsol commented 3 years ago

Lambdas have some long history. Initially, they were supposed to be used for passing to higher-order functions. After I had implemented placeholders, that syntax has become less significant, as you can simple write double = _ * 2. Lambdas have become a bit more useful again once I had added the syntax for multiline definitions, which made it possible to define longer functions without any type annotations, just like the count example.

However, I'm thinking about generalizing the current syntax for function definitions, so that you could skip type annotations completely (or only for some arguments):

func double(x) def
    return x * 2

This would be roughly equivalent to (just like double = _ * 2 is):

func double<T1,T2>(x: T1): T2 def
    return x * 2

It would be more powerful than lambdas, since default values and named arguments would still work. Therefore lambdas would be practically useless again, except for some rare cases where the placeholder syntax would not suffice. I would probably remove the syntax for multiline lambdas then, as it can't be used inside expressions anyway.

sirex commented 3 years ago

As I understand, placeholders does not support multiple arguments?

double = _1 * _2
adamsol commented 3 years ago

They do, but currently you can use each argument only once:

mul = _ * _

I've been thinking about indexed placeholders, but I'm not sure it would be readable enough. For situations where it would be necessary, an explicit lambda is probably better.

adamsol commented 3 years ago

I have implemented implicit generic functions (so type annotations in functions are now optional) and removed multiline lambdas.