0

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?

Fabien Sa
  • 9,135
  • 4
  • 37
  • 44
J du Preez
  • 145
  • 9
  • 3
    Can you post the actual code? `&1` is not valid syntax if that's the complete code and you should be getting an error about that. – Dogbert Jun 08 '17 at 08:46
  • @Dogbert elaborated as requested. Thank you. – J du Preez Jun 08 '17 at 13:53
  • 1
    I can't see an issue with the code you posted. I suspect the problems is coming from how you are processing the results of the fun. You should post the the `ServiceX.update_holdings` implementation. – Steve Pallen Jun 08 '17 at 14:20
  • @StevePallen Thank you for pointing me in the right direction. You helped me to answer my own question. Thanks! – J du Preez Jun 12 '17 at 13:35

1 Answers1

0

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
J du Preez
  • 145
  • 9
  • @StevePallen you were completely right. I made the noob mistake in the update_holdings method. Thanks for pointing me in the right direction. – J du Preez Jun 12 '17 at 13:32