gpt4 book ai didi

pattern-matching - 通过传递给当前函数的字段的子集匹配结构

转载 作者:行者123 更新时间:2023-12-01 23:35:10 24 4
gpt4 key购买 nike

我正在构建过滤 API。简化事情,我有一些类似于接受结构列表和过滤器映射的函数的东西。我的问题是 Enum.filter&match? 的配对在传入函数参数时不起作用:

def filter_structs(structs, filters) do
# this always returns []
structs |> Enum.filter(&match?(^filters, &1))
end

但如果我对过滤器进行硬编码,一切都会正常进行:

def filter_structs(structs, _filters) do
structs |> Enum.filter(&match?(%{some_field: true}, &1))
end

我有这个解决方法,但它不是很漂亮...没有更好的解决方案吗?

def filter_structs(structs, filters) do
structs
|> Enum.filter(fn s ->
Map.equal?(filters, s |> Map.take(filters |> Map.keys))
end)
end

最佳答案

可以使用 %{^key => _} 对变量 key 和使用 %{^ 的变量键值对进行模式匹配键 => ^值}

使用match?(^filters, map) 匹配整个 map 只会返回true 如果map === filters,则不会包含它。

以下实现利用了模式匹配,可能更清楚其意图:

  def filter_structs(structs, filters) do
Enum.filter(structs, fn struct ->
Enum.all?(filters, fn {field, value} ->
match?(%{^field => ^value}, struct)
end)
end)
end

关于pattern-matching - 通过传递给当前函数的字段的子集匹配结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65733143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com