expr icon indicating copy to clipboard operation
expr copied to clipboard

Feature request:two builtin array functions

Open huziu235 opened this issue 1 year ago • 5 comments

some(array,n,predicate) Return true immediately when match n item , otherwise return false filterN(array,n,predicate) Return first n matches immediately, or all matches if matches less than n.

largeArray|some(2,#>100)

largeArray|filterN(n,#>100)

huziu235 avatar Jun 12 '24 03:06 huziu235

Hey @huziu235

What about, instead of introducing new builtins , we can solve this on optimizer level. For example, Expr already supports those optimization:

  • filter(array, # > 100)[0] converts to find(array, # > 100)
  • filter(array, # > 100) | last() converts to findLast(array, # > 100).
  • array | filter(array, # > 100) | map(# ^ 2) converts to a single filter step which applies map.
  • and more https://github.com/expr-lang/expr/tree/master/optimizer

Lets add new optimization for those cases:

// Return true immediately when match n item , otherwise return false
count(largeArray, # > 100) >= 2

We can add an optimization which will do an early exit from count in case 2 or more element are found.

And this optimization:

// Return first n matches immediately, or all matches if matches less than n.
filter(largeArray, # > 100) | take(n)

Let's also add an early exit from filter as soon as n elements are found.

antonmedv avatar Jun 12 '24 19:06 antonmedv

Expr already has len(filter()) to count() optimizer, so even this case will work:

len(filter(largeArray, # > 100)) >= 2

antonmedv avatar Jun 12 '24 19:06 antonmedv

@antonmedv hi When I use filter function,How can I get index from the predicate?

ctcx avatar Aug 25 '24 10:08 ctcx

Via #index .

antonmedv avatar Aug 25 '24 11:08 antonmedv

hi dear @antonmedv : I have three arrays, A, B, and C. I want to iterate over array A, compare the values at the same position in arrays A and B, and if they are equal, set the corresponding value in array C to the value at the same position in array A. Otherwise, insert the value at the same position in array B at the beginning of array C.

How can this be done?

ctcx avatar Aug 28 '24 03:08 ctcx