kcl-lang / kcl-lang.io

Source of the KCL Website. https://kcl-lang.io
https://kcl-lang.github.io
Apache License 2.0
12 stars 33 forks source link

Support for func/function keyword syntax #368

Closed dennybaa closed 2 months ago

dennybaa commented 2 months ago

Hello,

I'm totally able to use functions in KCL and this is awesome. But it would be nice to have syntax support for this:

schema Config:
    mixin [
        AppIdMixin
    ]
    [...str]: any
    team: str
    teamName?: str
    cluster?: str
    project?: str
    env?: str
    baseId?: str
    appId?: any

protocol AppIdProtocol:
    team: str
    project?: str
    env?: str

mixin AppIdMixin for AppIdProtocol:
    baseId = "-".join([e for e in [team, project, env] if e])
    appId = lambda name: str -> str {
        "${baseId}-${name}"
    }

Functions are operational, though I'm not sure with how many positional arguments, one argument works at least... To achieve this scenario a workaround setting type to any appId?: any is required, it would great to have ability to support this with some native syntax... WDYT @Peefy ?

Thank you very much!

Peefy commented 2 months ago

I see. I think it is a good suggestion to continuously supplement the KCL type system, and the community will carefully consider the balance between simplicity and feature richness.

Currently, a walk around approach I think maybe as follows:

appId = lambda names: [str] -> str {
    assert len(names) >= 1 if names, "names must have one argument"
}
dennybaa commented 2 months ago

Yep, I mean since the functions and mixins are out there already, definitely someone will try to use mixed-in functions. What more important rather than arguments imo, is that a user has an explicit notion that the attribute is a function. In my opinion it brings a bit more clarity, when say it declarations could support complementary syntax such as:

schema Config:
    mixin [
        AppIdMixin
    ]
    appId: function str -> str # not just any
    # or maybe just
    # appId: function

mixin AppIdMixin for AppIdProtocol:
     appId = lambda name: str -> str {
        "${baseId}-${name}"
    }

The above provides more content on what the actual attribute is, automatically suggesting that even if this is a non-hidden attribute it won't ever appear in a structure or anywhere... So my point is solely about explicitness, apart from that it already works as charm))

Peefy commented 2 months ago

I see.

Do you mean this code with the function type annotation?

schema Config:
    mixin [
        AppIdMixin
    ]
    appId: (str) -> str

mixin AppIdMixin for AppIdProtocol:
     appId = lambda name: str -> str {
        "${baseId}-${name}"
    }
dennybaa commented 2 months ago

Yep, this is that what I mean if favoring js lambda syntax...