Recursion and Refactoring Our Solar Flares

This is a premium course, which you can purchase below.

Buy Now

Most developers know about recursion and have used it once or twice in their careers; perhaps more. It can be quite difficult to get right - this is not the case with Elixir. With a combination of pattern matching and the head/tail functionality of Lists, recursively iterating over lists is straightforward.


I'm exhausted. I called in sick today... I've been up for 28 straight hours which isn't so bad... I guess but WOW was it cold last night. I think I came down with rickets or something.

Anyway the Science Team reviewed the Solar Flare stuff you did and they said it was "OK". They didn't give their feedback to the CTO yet because they wanted some changes made - we get to do that today.

The first thing they want is to understand what the total exposure to all of the flares amounts to. This is a simple summing calculation you should be able to do easily - but the Science Team is being rather micro-manager-y about all of this and they want to evaluate some different ways that we can run the calcs.

Sometimes I like my job... other times...

Using Recursion

With a combination of pattern matching and the head/tail functionality of Lists, recursively iterating over lists is quite simple:

def total_flare_power(list)  do
  total_flare_power(list, 0)
end

def total_flare_power([], total),  do: total

def total_flare_power([head | tail], total) do
  new_total = power(head) + total
  total_flare_power(tail, new_total)
end

Let your eyes wander on that for a second, and then I'll explain a bit.