erg-lang / erg

A statically typed language compatible with Python
http://erg-lang.org
Apache License 2.0
2.62k stars 54 forks source link

Add multiline method chain syntax #393

Open mtshiba opened 1 year ago

mtshiba commented 1 year ago

This syntax allows

x.foo().bar().baz(y)

to be rewritten as

x
    .foo()
    .bar()
    .baz(y)

Indentation is important,

x
.foo()

is invalid (this means sequential execution of x and .foo()).

zetashift commented 1 year ago

How about making this work with |> instead? Makes things a bit more "functional pipeline"-ey to use.

x
    |> (_.foo())
    |> (_.bar())
    |> (_.baz(y))

I guess it sacrifices readability a lot more... Also see https://github.com/fsharp/fslang-suggestions/issues/506 for a similiar discussion

mtshiba commented 1 year ago

The pipeline operator already exists in Erg.

True |> assert()
assert -1 + -1 |> .abs() == 2

It might be a good to add the rule regarding this operator.

zetashift commented 1 year ago

Oh cool! Ignore me then :P

bmitc commented 1 year ago

@zetashift This isn't entirely related to Erg, but for what it's worth since this issue was linked to an F# issue, F# actually allows method chaining.

type Test() =
    member this.A () = this
    member this.B () = this
    member _.C () = ()

let test = Test()

test.A()
    .B()
    .C()

// or

test.A().B().C()

The linked feature of allowing _ is to support other different use cases and probably wouldn't be recommended just for method chaining using |>.

While strange indentation like

test
    .A()
    .B()
    .C()

is allowed in F#, it isn't recommended. That might be relevant to the original proposal here for Erg.