Search code examples
recursionfilteringpurely-functionalanuraffl

filter max of N


Could it be possible to write in FFL a version of filter that stops filtering after the first negative match, i.e. the remaining items are assumed to be positive matches? more generally, a filter.

Example:

removeMaxOf1([1,2,3,4], value>=2)

Expected Result:

[1,3,4]

This seems like something very difficult to write in a pure functional style. Maybe recursion or let could acheive it?

Note: the whole motivation for this question was hypothesizing about micro-optimizations. so performance is very relevant. I am also looking for something that is generally applicable to any data type, not just int.


Solution

  • I have recently added find_index to the engine which allows this to be done easily:

    if(n = -1, [], list[:n] + list[n+1:])
    where n = find_index(list, value<2)
    where list = [1,2,3,4]
    

    find_index will return the index of the first match, or -1 if no match is found. There is also find_index_or_die which returns the index of the first match, asserting if none is found for when you're absolutely certain there is an instance in the list.

    You could also implement something like this using recursion:

    def filterMaxOf1(list ls, function(list)->bool pred, list result=[]) ->list
    base ls = []: result
    base not pred(ls[0]): result + ls[1:]
    recursive: filterMaxOf1(ls[1:], pred, result + [ls[0]])