Re: Flattening a list
Re: Flattening a list
- Subject: Re: Flattening a list
- From: Paul Berkowitz <email@hidden>
- Date: Sat, 15 May 2004 22:41:36 -0700
On 5/15/04 6:21 PM, "Michelle Steiner" <email@hidden> wrote:
>
Usually, when concatenating items to the end of a list, it's better to
>
use copy rather than set.
Not true: 'set end of list to x' requires less memory than 'copy x to end of
list'. You might be getting this mixed up with the need to use 'copy' when
not wanting to 'data share' a list with another variable represnting the
list - i.e. if you want the original list to remain as is while you
manipulate a copy of it, use 'copy'.
>
However, when trying to flatten a list, you
>
have to use set.
>
>
set variable to "zzz"
>
set a to {{1, "z", 3}, {variable, "b", "c"}, {5, "text", variable}}
>
set b to {}
>
repeat with i from 1 to count of a
>
copy item i of a to end of b
>
end repeat
>
b
>
>
--> {{1, "z", 3}, {"zzz", "b", "c"}, {5, "text", "zzz"}}
That's exactly what you told it to do. You didn't concatenate it at all.
You'd get exactly the same, but better memory usage (makes no difference
with a list this size), with
set variable to "zzz"
set a to {{1, "z", 3}, {variable, "b", "c"}, {5, "text", variable}}
set b to {}
repeat with i from 1 to count of a
set end of b to item i of a
end repeat
b
--> {{1, "z", 3}, {"zzz", "b", "c"}, {5, "text", "zzz"}}
Concatenating is what flattens the list.
>
set variable to "zzz"
>
set a to {{1, "z", 3}, {variable, "b", "c"}, {5, "text", variable}}
>
set b to {}
>
repeat with i from 1 to count of a
>
set b to b & item i of a
>
end repeat
>
b
>
>
--> {1, "z", 3, "zzz", "b", "c", 5, "text", "zzz"}
>
>
Is there a better way to flatten a list than looping like this?
You could omit one concatenation, FWIW:
set variable to "zzz"
set a to {{1, "z", 3}, {variable, "b", "c"}, {5, "text", variable}}
set b to item 1 of a
repeat with i from 2 to count of a
set b to b & item i of a
end repeat
b
--> {1, "z", 3, "zzz", "b", "c", 5, "text", "zzz"}
--
Paul Berkowitz
_______________________________________________
applescript-users mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/applescript-users
Do not post admin requests to the list. They will be ignored.