[Cuis-dev] Methods that return multiple values

Christian Haider mail at christianhaider.de
Wed Jun 21 06:37:31 PDT 2023


I added something similar to my Values package (VW and ports).

The source is

SequenceableCollection>>asArgumentsIn: aBlock

     "Evaluate aBlock with the receiver's elements as parameters.

     aBlock takes its arguments from the receiver.

     'ok'

     #(1 2 3) asArgumentsIn: [:a :b :c | a + b + c]

     #(1 2 3) asArgumentsIn: [:a :b | a + b]

     #(1 2 3) asArgumentsIn: [:a | a]

     #(1 2 3) asArgumentsIn: [42]

     'not ok'

     #(1 2 3) asArgumentsIn: [:a :b :c :d | a + b + c + d]

     "

 

     ^aBlock cullWithArguments: self asArray

 

The difference is that it takes a list of any size and picks out the first items and binds them to the variables.

I use it often for CSV processing like

                (line tokensBasedOn: $;) asArgumentsIn: [:first :second :y | … ].

 

I am just a bit unhappy with the name – it is too long. It reads ok though.

The pipe character is an interesting idea. I have to think about it.

 

I am use it for a while now and I am very happy with it.

 

Happy hacking,

Christian

 

 

Von: Cuis-dev <cuis-dev-bounces at lists.cuis.st> Im Auftrag von Luciano Notarfrancesco via Cuis-dev
Gesendet: Mittwoch, 21. Juni 2023 15:13
An: Discussion of Cuis Smalltalk <cuis-dev at lists.cuis.st>
Cc: Luciano Notarfrancesco <luchiano at gmail.com>
Betreff: [Cuis-dev] Methods that return multiple values

 

Smalltalk doesn’t have a convention for methods returning multiple values, and I’m not aware of any implementation.

An example of such thing is the extended gcd: ‘a xgcd: b’ returns g, s, t where g is the gcd, and as + bt = g. Writing methods that return multiple values is easy with the curly brackets syntax, Integer>>#xgcd: ends with something like

    ^ {g. s. t}

But using sending messages that return multiple values is kind of annoying, I end up doing something like:

    xgcd := a xgcd: b.

    g := xgcd at: 1.

    s := xgcd at: 2.

    t := xgcd at: 3

Some years ago I thought about using blocks for this, but I never tried it. Today I just did a little experiment implementing anArray | aBlock as ‘^ aBlock valueWithPossibleArgs: self’ and I can do:

    (a xgcd: b) | [:g :s :t| … ]

 

This is seems quite nice already, I guess I’ll start using it and see how it feels. But the point of this mail is not to show a solution, but to ask if anyone have thought about this or if they know any nicer solutions. Any ideas?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.cuis.st/mailman/archives/cuis-dev/attachments/20230621/e6c03302/attachment.htm>


More information about the Cuis-dev mailing list