Infinite Loop Dreams
“How do I get out…how do I get out? If I don’t exit this loop, I won’t get up in time for school. What code do I need!?!?
1 2 3 4 5 |
|
I wake up in a panic, but also happy I’m out of that damn inifinite loop trying to sabotage my life. 12:13am. I’ve been asleep for an hour and a half.
I go back to sleep.
Besides leading to a questioning of my sanity, this dream made me ponder why exactly infinite loops exist in Ruby and other coding languages.
Why would such a thoughtful, powerful thing allow you to do something which could break it? Shouldn’t Ruby be able to do an unoticeably fast scan of your code before it interprets each line to check for an inifinite loop and let you know?
I’m not suggesting that it should. I’m just trying to wrap my head around it.
Give me a second while I google this…
Ok. I’m back.
Apparantly, Alan Turing thought of this problem before the advent of modern computers…in 1936!
The problem of determining whether a loop is infinite or not is called “The halting problem”
He said that an algorithm to solve this problem cannot exist. “One approach to the problem might be to run the program for some number of steps and check if it halts. But if the program does not halt, it is unknown whether the program will eventually halt or run forever.”- wikipedia
Basically the computer can never know whether at some point the loop will end or not. Maybe if it keeps going, in 3 years the loop will end. It doesn’t know that for sure.
Although still, you’d think there are certain circumstances where we could know for sure that the loop is inifinite and tell the computer to recognize those instances.
1 2 3 4 5 6 7 |
|
Wow, don’t want to do that again. This must have run 1000 times in irb in the time that it took me to hit control+c and abort.
Given a loop like the one above, can’t we tell Ruby to flag it in some way? I assume there is a way to do that. I assume it wouldn’t be extremely difficult to do. But there would probably be consequences. By doing that, we’d be setting limits on ourselves.
Maybe there are things we do want to run forever until we define some other code to stop it.
The halting problem is a symbol of the power we have over our computers. If we want the computer to repeat something a bizzillion times till we tell it to stop, we can. I don’t have any friends that I can say the same for.
Thankfully, in Ruby, this is not a problem I find myself having very often anway. We can iterate using the .each and .times methods, which can allow us to circumvent “while”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|