Reputation: 19466
I've written a statement as follows:
case length(clicks) do
0 ->
date_list = []
1 ->
date_list = start_date
_ ->
date_list = Interval.new(from: start_date, until: end_date) |> Enum.to_list
end
It seems like date_list
is never set. What am I doing wrong?
Upvotes: 2
Views: 1372
Reputation: 121000
While the answer by Denis is technically correct, using Kernel.length/1
is a bad practice in general, since it traverses the whole list.
Use direct pattern matching instead:
date_list =
case clicks do
[] -> []
[_] -> start_date
[_ | _] ->
[from: start_date, until: end_date]
|> Interval.new()
|> Enum.to_list()
end
Also note, that Elixir guidelines enforce to start the pipe with a raw value and always use parentheses in calls to functions.
According to the scoping issue in your initial question, since there is no assignment to variable in Elixir, as well as there are no variables at all, the compiler cannot have Schrödinger local date_list
. Remember: date_list = ...
is not an assignment, it’s rebinding.
Upvotes: 5
Reputation: 9841
You are assigning internal variables inside the "case" statement. Assign the variable externally like this:
date_list = case length(clicks) do
0 ->
[]
1 ->
start_date
_ ->
Interval.new(from: start_date, until: end_date) |> Enum.to_list
end
Upvotes: 3