I was organizing my hard drive and came across one of the first julia programs I ever wrote. It turns out this actually was quite a while ago; the timestamp is July 5, 2013. It was an enlightening exercise reading the code and then rewriting it with the benefit of three more years of experience.

## Old Code

So here's the code:

old_version = function(n)

field = trues(n)

for i in primes(n)
field[i] = false
x = 1
while i + 2x*x <= n
field[i + 2x*x] = false
x += 1
end
end

i = 3

while i < n
if field[i]
return(i)
end
i += 2
end

return("Unsuccessful")

end


Let me start off by saying, while I would be embarrassed by this code today, I think it's not bad for a beginner.

I'm going to slightly obscure the purpose behind the program 1. Suffice to say that I'm looking for the first odd composite number that can't be written as the sum of a prime number and twice a perfect square. The interesting stuff isn't the code anyways, it's the style. Here are some things to note:

• The spacing is huge; this was the first thing that struck me. It's only 25 lines, but it just feels really spread out.
• It's obvious that I'm coming from R. I end up define an anonymous function (back when they were slow) and return a tuple. Why? Because that's what the R code would look like.
• I name things terribly; what is n? Also, I use single letter variable names.
• I have bad algorithmic thinking. I make it needlessly more complicated than I should have; see the new code below.
• No type stability. I either return an integer or an ASCII string.

## New Code

Ok, presumably I've learned a few things over the past couple years. I should be able to do better. So I rewrote it.

function new_version(searchMax)

for ii = 3:2:searchMax
xx = 1
pairFound = false
while !pairFound && ii - 2xx^2 > 0
xx += 1;
end
!pairFound && return ii
end

throw(ErrorException("No cases found below \$searchMax"))
end


It's shorter, more idiomatic, understandable, and runs faster.

It also just feels better. I can't quite explain it, but just looking at the code blocks from a distance, not even reading them, the second feels good. I seem to have developed taste idiosyncratic as it may be.

## Conclusion

This raises the question, what if I come back to this code in three more years? Will I have the same reaction as I did to my previous one? Or will the learning curve have leveled off?

For short stuff like this I probably can't do much better. There are only so many ways to write it. However, I might become better at writing larger projects. Or I might switch paradigms; perhaps three years from now I'll wonder at my naivete in writing imperative programs.

## Footnotes:

1

If you recognize it you'll understand why.