I need to break my for loop in case of an thrown message and append s to the result list. Breaking the loop works, but my result is empty. I can not use Table[] because it does not support Break[].
EDIT: s has the form of list, so I get a Table structure for result
EDIT 2: AppendTo[] yields empty result too.
result = {};
For[i = 0, i < 6, i++,
s = {Quiet[
Check[If[i == 3, Message[FindRoot::jsing, x, 1], i], "Nan",
FindRoot::jsing]]};
If[s == "Nan", Break[], AppendTo[result, s]];
]
result
yields:
{}
Any help appreciated.
Appendbeing evil in loops) is not it. It is that the full list is copied to append a single element. – Leonid Shifrin Apr 19 '12 at 17:35AppendTo's implementation equally eager to copy things repeatedly? I can imagine an implementation where theAppendversion is forced to copy with every operation, but whereAppendTois implemented much like C++'sstd::vectorand only has to copy some of the time instead of on every step. I just ran someTimings and it looks like their behavior is almost identical. – sblom Apr 19 '12 at 17:48old = {new, old}to grow a list, but do you have any insights on the performance ofJoin? For example,{new} ~Join~ oldvs.old ~Join~ {new}? If it's better thanAppendand only marginally worse than linked lists, then it provides a way to add quickly and have easy access to an arbitrary element. I use this at times for moderately sized lists and found it quite convenient. However, I don't know (and haven't spent time poking) howJoinworks and whether it copies the entire list too... thoughts? – rm -rf Apr 19 '12 at 18:17Joinsurely copies lists, it has no other choice :). So, it is no better thanAppend, at least conceptually (I do not remember the results of micro-benchamrking and am actually being increasingly annoyed by the fact that the language encourages this massive waste of time and effort). Using linked lists is different because at every given iteration, there are only two elements in the list - a newly added one and a pointer to the old list. The fact that pointers are not available to us explicitly, is irrelevant - the point is that there is no massive copying. – Leonid Shifrin Apr 19 '12 at 18:54AppendTois just as bad in this regard asAppend. Moreover, you can see thatAppendTohas been actually implemented withSetandAppend, by usingOn[Set], and then saya = Range[5]; AppendTo[a, 6]. – Leonid Shifrin Apr 19 '12 at 19:31