【问题标题】:filter max of N过滤器最大值 N
【发布时间】:2018-05-23 16:54:42
【问题描述】:

是否可以在 FFL 中编写 filter 的版本,在第一次否定匹配后停止过滤,即假设其余项目为肯定匹配?更一般地说,一个过滤器。

示例:

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

预期结果:

[1,3,4]

这似乎很难用纯函数式编写。也许递归或let 可以实现它?

注意:这个问题的全部动机是假设微优化。所以性能非常重要。我也在寻找一般适用于任何数据类型的东西,而不仅仅是int

【问题讨论】:

  • 递归不删除纯函数。还是这样?

标签: recursion filtering purely-functional anura ffl


【解决方案1】:

我最近在引擎中添加了find_index,这可以轻松完成:

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

find_index 将返回第一个匹配项的索引,如果没有找到匹配项,则返回 -1。还有find_index_or_die,它返回第一个匹配的索引,当你绝对确定列表中有一个实例时断言是否找不到。

你也可以使用递归来实现类似的东西:

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]])

【讨论】:

  • 酷!但不应该是 list[:n] + list[n+1:] 而不是 list[n:] 吗?我已对您的回答进行了修改。
  • 很有启发性!但是对于 base not pred(ls[0]): result + ls 不应该是 base not pred(ls[0]): result + ls[1:] 吗?我已对您的回答进行了修改。
  • 这很好。请有人评论调试控制台友好版本?
【解决方案2】:

递归当然可以! :D

filterMaxOf1(input, target)
where filterMaxOf1 = def
        ([int] l, function f) -> [int]
        if(size(l) = 0,
                [],
                if(not f(l[0]),
                        l[1:],
                        flatten([
                                l[0],
                                recurse(l[1:], f)
                        ])
                )
        )
where input = [
        1, 2, 3, 4, ]
where target = def
        (int i) -> bool
        i < 2

一些检查:

--> filterOfMax1([1, ]) where filterOfMax1 = [...]
[1]
--> filterOfMax1([2, ]) where filterOfMax1 = [...]
[]
--> filterOfMax1([1, 2, ]) where filterOfMax1 = [...]
[1]
--> filterOfMax1([1, 2, 3, 4, ]) where filterOfMax1 = [...]
[1, 3, 4]

这种风格失去了一些强类型安全性,但更接近尾递归:

filterMaxOf1(input, target)
where filterMaxOf1 = def
        ([int] l, function f) -> [int]
        flatten(filterMaxOf1i(l, f))
where filterMaxOf1i = def
        ([int] l, function f) -> [any]
        if(size(l) = 0,
                [],
                if(not f(l[0]),
                        l[1:],
                        [
                                l[0],
                                recurse(l[1:], f)
                        ]
                )
        )
where input = [
        1, 2, 3, 4, ]
where target = def
        (int i) -> bool
        i < 2

【讨论】:

  • 我的问题有误。对于条件,它应该说value &lt; 2。也许我应该将其称为 removeMaxOf1 条件值>1
  • 我进一步编辑 - 只需添加一个合适的 not 就可以开始解决一个问题。
  • 我注意到 flatten 会进行深度展平,因此该算法不会普遍适用,例如如果我的数据值是列表。
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多