Programming Elixir book, Lists and recursion question

I’ve been working my way through the programming elixir book, and I wanted to ascertain whether or not the way I answer a particular question was in line with what was intended.

Some of the question sections seem to pertain more so to learning sections two steps prior, rather than the immediately preceding section.

For example I just finished the question:

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

The below…

  def span(from, to) when not is_integer(from) or not is_integer(to) do
    IO.puts("two integers required");
  end

  def span(from, to) when from == to, do: [to]

  def span(from, to) when from < to do
    [from|span(from + 1, to)]
  end

  def span(from, to) when from > to do
    [from|span(from - 1, to)]
  end

…does the job, but the actual reading section itself was regarding list recursion as it pertained to filtering, and using recursive pattern matching, that is [head = [_, hello, _, _] | func(tail)]. I did not have to do either of these things here, not even to make to make the code look cleaner.

Did I not understand the question? Could I have tackled the problem so as to be more inline with what I had just learnt?

But you did use recursive pattern matching.? i.e. you call span in span and pattern match your way out when from == to (you could’ve also matched it like span(to, to) indicating both are same value by matching it to one ‘to’ variable)

2 Likes

I understand, but this was already covered in prior chapters, and questions were already given that required such implementation (and more).

Btw, thanks for the tip regarding span(to, to) I’ll definitely be using that in other implementations.

Would my implementation benefit from nested/chained pattern matching, that is, something like [head = [_, hello, _, _] | func(tail)]?

I can’t speak to the specific intent in this case, but a common tactic in teaching is to repeat material (or exercises) after a pause to improve retention.

1 Like

Thanks everyone, I did suspect this to be the case, I just wanted to make sure I wasn’t missing the point with this question or others as it had happened with a couple of prior chapters.