expr-lang/expr

Feature request:two builtin array functions

huziu235 opened this issue · 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)

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.

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

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

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

Via #index .

ctcx commented

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?