cjm2671
cjm2671

Reputation: 19466

Elixir case statement

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

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

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

denis.peplin
denis.peplin

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

Related Questions