在列表中的过滤元素上作用
我收集了来自数据源的记录集合,表示{:person,_},{:dog,_} for dog等。我想根据记录的条件返回记录的修改版本是“:人”。
db = [
{:dog, %{name: "Sparky", age: 4}},
{:person, %{name: "Jeff", age: 34}},
{:person, %{name: "Suzan", age: 41}},
{:dog, %{name: "Bella", age: 8}}
]
我想返回:
[{:person, "Jeff", 34}, {:person, "Suzan", 41}]
我已经尝试过:
db |> Enum.map(fn {:person, data} -> {:person, data.name, data.age} end)
但是我在不匹配的情况下错误:狗
吗?
I have a collection of records from a data source denoting {:person, _} for person, {:dog, _} for dog, etc. I'd like to return a modified version of the record based on the condition that the record is that of ':person'.
db = [
{:dog, %{name: "Sparky", age: 4}},
{:person, %{name: "Jeff", age: 34}},
{:person, %{name: "Suzan", age: 41}},
{:dog, %{name: "Bella", age: 8}}
]
I'd like to return:
[{:person, "Jeff", 34}, {:person, "Suzan", 41}]
I've tried:
db |> Enum.map(fn {:person, data} -> {:person, data.name, data.age} end)
But I'm erroring on non-match for :dog
Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种简单的方法是使用a 理解。
综合是长精灵中的强大工具,可让您从具有匹配规范的列表中滤除数据(除其他方面)。上面的代码段仅在列表中的2个元素元组中迭代,其中第一个元素是
:person
arom。所有其他条目都被过滤了。当然,理解比这更强大。如果您想强制执行所有返回的记录都包括一个名称和年龄属性,则可以执行类似的操作:上面只能返回2个元素元组的条目,具有
:person
作为第一个元素,<代码>:Age 和:数据中的name
键,以及年龄是整数,名称是二进制文件。One easy way to do this is by using a Comprehension.
Comprehensions are a powerful tool in Elixir that allow you to filter out data from a list with a match spec (among other things). The above code snippet will only iterate over items in the list that are 2 element tuples, having the first element be the
:person
atom. All other entries are filtered out. Of course, comprehensions are more powerful than this. If you wanted to enforce that all records returned included a name and age attribute you could do something like this:The above will only return entries that are 2 element tuples, having
:person
as the first element,:age
and:name
keys in the data, and where age is an integer and name is a binary.首先,您需要过滤要使用要使用的元素,因此应该像该
地图一样采用输入元素,并创建新的枚举,并以函数为参数作为映射函数的函数返回值。
过滤器创建新的枚举,仅包含给定函数返回true的元素仅包含元素
First You need to filter out elements You want to use, so it should be like this
Map is just taking input elements and creates new Enum with returned values from function given as argument to map function.
Filter creates new Enum which contains only element where given function return true