Surprising behavior of dolist with break condition.
Posted: Fri Apr 03, 2015 7:32 am
This affects dotimes, dolist, and the rest of the family.
I had a situation where I needed to scan through a list of numbers, and find the list index of the number that is just less than my target number.
Example:
With the break condition, the loop always returns true. This isn't what I expect; I expect the last value evaluated inside the form, not the condition test. I want to abort the loop as soon as I find the value I'm looking for. Is this wrong? It affects pretty much all the looping constructs, and was very surprising to me. Without the break condition, the loops return the last value evaluated in the body.
Also, is there a better idiom to do such scanning, some sort of binary search function?
I understand it is useful to know whether the break condition was triggered or not, couldn't that be saved in a system variable $brk the way regex output is? Also, even leaving $idx behind after a form evaluation would be nice too.
I had a situation where I needed to scan through a list of numbers, and find the list index of the number that is just less than my target number.
Example:
Code: Select all
(set 'foo '(1 5 10 20 100 105))
(dotimes (i (+ -1 (length foo)) (> (foo i) 50)) (foo i))
=> true
;; was expecting return value of 20 (last value before triggering break condition)
Also, is there a better idiom to do such scanning, some sort of binary search function?
I understand it is useful to know whether the break condition was triggered or not, couldn't that be saved in a system variable $brk the way regex output is? Also, even leaving $idx behind after a form evaluation would be nice too.