I want to iterate over a list, and return the index as long as I found the first element satisfying my condition. Written in a for loop:
f[x_]:=2x
For[i=1, i<=10, i++,
If[f[i]==10, Return[i]]
]
And I know a way to write this in Mathematica:
Position[f/@Range[10], 10, 1, 1]
However, in this code, a list of f[1], f[2], ..., f[10] is all calculated before the Position executes. In my real problem, f is a costly function. I don't want to, and it is unnecessary to calculate the rest when the first is found. How can I do this using functional style of Mathematica (no loops, ++s)?
Thanks
ScanwithThrowandCatch( see the "Generalization and extension" sections of theScandocs for an example). However, perhaps you could provide the context in which this need arose. It may be that refactoring the parent problem might lend itself to a more idiomatic solution and better performance. Otherwise, this would actually seem an acceptable use of a procedural loop, at least to me. – MarcoB Jul 12 '16 at 15:02nn = 0; Scan[If[f[#] <= 10, nn++, Return[nn]] &, Range[10]]would work also – Jason B. Jul 12 '16 at 15:05fbut has generally the same framework of this problem. – Nick Jul 12 '16 at 15:22