【问题标题】:Elixir List Comprehension to Create a New List of StructsElixir List Comprehension 以创建新的结构列表
【发布时间】:2017-11-09 20:55:01
【问题描述】:

我对 Elixir 很陌生,并试图使用列表推导生成一个新的结构列表,而对于我的生活,我似乎无法做到这一点:

holdings = ServiceX.update_holdings(
         fn() -> for n <- 1..3, do: n end,
         &(for n <- 1..100, do: %Holding {
                                  client_id: &1,
                                  company_id: n,
                                  company: "---",
                                  revenue: 0.0 }
         ))

update_holdings 接受另一个返回结构列表的函数。真正的实现调用数据库。此代码用于 ExUnit 测试,我正在尝试返回一些存根数据。

似乎我在这里遇到了一些明显的错误。这是我运行时遇到的错误:mix test

** (Protocol.UndefinedError) protocol Enumerable not implemented for 
   %Holding{client_id: 1, company: "---", company_id: 1, revenue: 0.0}

我是否缺少模块导入,或者如何使用列表推导生成结构列表?

【问题讨论】:

  • 你能发布实际代码吗? &amp;1 是无效的语法,如果这是完整的代码,你应该得到一个错误。
  • @Dogbert 根据要求详细说明。谢谢。
  • 我看不出您发布的代码有问题。我怀疑问题出在你如何处理乐趣的结果。您应该发布 ServiceX.update_holdings 实现。
  • @StevePallen 感谢您为我指明正确的方向。你帮我回答了我自己的问题。谢谢!

标签: elixir list-comprehension elixir-mix ex-unit


【解决方案1】:

不正确的代码:

def update_holdings(f1, f2) do
     ids = f1.()
     for id <- ids,
         holdings <- f2.(id),
         holding <- holdings,
         do: holding
 end

问题在于额外的嵌套枚举holding &lt;- holdings。这是一个业余错误,因为我误解了它在 Elixir 中的工作原理。 将上述更改为以下解决了问题:

def update_holdings(f1, f2) do
     ids = f1.()
     for id <- ids,
         holding <- f2.(id),
         do: holding
 end

【讨论】:

  • @StevePallen 你完全正确。我在 update_holdings 方法中犯了菜鸟错误。感谢您为我指明正确的方向。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2017-02-20
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
相关资源
最近更新 更多