ballerina-platform / ballerina-spec

Ballerina Language and Platform Specifications
Other
168 stars 53 forks source link

Add stream to array conversion function to standard lib #1316

Open Shadow-Devil opened 1 month ago

Shadow-Devil commented 1 month ago

Description: This Stackoverflow question says, that there are two ways to convert a stream to an array, but in my opinion both of them seem quite verbose.

It would be great to have a stream:toArray() function, which is the opposite of array:toStream() and would convert a stream to an array. In the documentation of the function it should be noted, that for infinite streams this will loop forever.

What do you think about this?

Suggested Labels:

Code sample that shows issue:

Related Issues:

jclark commented 1 month ago

I think that's a good addition.

One question is can we write the type for this.

public isolated function toArray(stream<T,E|()>) returns E|T[] = external;

Would that work @MaryamZi ?

MaryamZi commented 1 month ago

I also agree that this would be a good addition. Especially with database clients, we often see functions/query expressions introduced to do just this.

One question is can we write the type for this.

public isolated function toArray(stream<T,E|()>) returns E|T[] = external;

Would that work @MaryamZi ?

I believe this should work, similar to stream:reduce, which is defined as

@typeParam
type Type any|error;

@typeParam
type Type1 any|error;

@typeParam
type ErrorType error;

public isolated function reduce(stream<Type,ErrorType?> stm, 
         @isolatedParam function(Type1 accum, Type val) returns Type1 func, Type1 initial)
   returns Type1|ErrorType = external;

(We do seem to have a bug with stream:reduce type checking in the jBallerina implementation when the completion type is a subtype of error - https://github.com/ballerina-platform/ballerina-lang/issues/43209)