Reputation: 145
I'm quite new to Elixir, and trying to yield a new list of structs using list comprehension, and for the life of me I can't seem to get this right:
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
takes in another function that returns a list of of structs. The real implementation calls out to the database. This code is for an ExUnit test, where I'm trying to return some stubbed data.
Seems I'm getting something obvious wrong here. Here's the error I get when I run: mix test
** (Protocol.UndefinedError) protocol Enumerable not implemented for
%Holding{client_id: 1, company: "---", company_id: 1, revenue: 0.0}
So am I missing a module import, or how else do I produce a list of structs using list comprehension?
Upvotes: 0
Views: 465
Reputation: 145
Incorrect code:
def update_holdings(f1, f2) do
ids = f1.()
for id <- ids,
holdings <- f2.(id),
holding <- holdings,
do: holding
end
The problem is the extra nested enumeration holding <- holdings
. This is a amateur mistake because I misunderstood how it works in Elixir.
Changing the above to the following fixed the problem:
def update_holdings(f1, f2) do
ids = f1.()
for id <- ids,
holding <- f2.(id),
do: holding
end
Upvotes: 0