small medium large xlarge

Screen shot 2015-06-25 at 4.39.41 pm_pragsmall
01 Jul 2015, 05:24
Vincent Franco (1 post)

Write a function MyList.span(from,to) that returns a list of the numbers from up to to.

Not sure if I completed this exercise correctly. I approached it using the recursive pattern matching as described in the previous example. But my solution feels strange. Elixir is new to me so I am reaching out to y’all

defmodule MyList do
  def span(from, to) do
    _span [to], from

  defp _span(list = [ from | _tail ], from), do: list

  defp _span([ head | tail ], from) do
     _span([head - 1] ++ [head | tail], from)

Is there a better way to approach this that the original authors had in mind? What feels weird to me is the concatenation…

19 Sep 2015, 00:06
James Van Lommel (2 posts)

I’m working through the book myself, so can’t answer for what the author had in mind. However,I think the list concatenation is fine: it’s a very fast operation to append to the front of a list, which is what you’re doing.

Looking at your code, it took me a second to understand that the first pattern is matched when the two terms named ‘from’ match in a recursive call. I’ll have to remember that.

My code is slightly different because I resorted to using normal guard clauses on the function.

def span(from, to) when from <= to, do: _span(from, to, [])
def _span(from, to, list) when from > to, do: list
def _span(from, to, list), do: _span(from, to - 1, [to | list])

The only minor difference is that the guard clause will reject cases where someone asks for a span with the high number first and then the lower number.