I'm in the same boat and also find that having a good goal can alleviate some of the pains of ADHD. In my case I like to set goals that I can easily visualize and associate with a tangible outcome. That way when I get off track, I can nudge myself in the right direction with reminders of what having the end product would be like.
An example is "implement XYZ paper" -> when you get off track, think about the algorithm running on your computer, how much faster it would be than the previous one, etc.
An example is "implement XYZ paper" -> when you get off track, think about the algorithm running on your computer, how much faster it would be than the previous one, etc.