Re: Flattening Nested Lists
Re: Flattening Nested Lists
- Subject: Re: Flattening Nested Lists
- From: "Nigel Garvey" <email@hidden>
- Date: Tue, 27 Jan 2009 00:46:45 +0000
Philip Aker wrote on Mon, 26 Jan 2009 04:53:45 -0800:
>on FlattenList(theList, outResult)
> repeat with i in theList
> if (class of i is list) then
> my FlattenList(i, outResult)
> else
> set end of outResult to contents of i
> end if
> end repeat
>end FlattenList
>
>set deep to {{"item 1", 0, {"item 3", "item 4", "item 5"}},
>{{name:"Michael"}, "item 7", "item 8"}, 999}
>set outResult to {}
>my FlattenList(deep, outResult)
>outResult
"Mark J. Reed" wrote on Mon, 26 Jan 2009 08:56:57 -0500:
>on flatten(aList)
> if class of aList is not list then
> return { aList }
> else if length of aList is 0 then
> return aList
> else
> return flatten(first item of aList) & flatten(rest of aList)
> end
>end flatten
>
>flatten({{1,2},3,{4,{5,{6,7},8}}})
Another alternative, which performs surprisingly well (with short lists
at least), uses nested repeats and concatenation instead of recursion:
on flattenList(theList)
repeat until (count theList's lists) is 0
set flatterList to {}
repeat with i from 1 to (count theList)
set x to item i of theList
if (x's class is list) then
set flatterList to flatterList & x
else
set flatterList to flatterList & {x}
end if
end repeat
set theList to flatterList
end repeat
return theList
end flattenList
set deep to {{"item 1", 0, {"item 3", "item 4", "item 5"}},
{{name:"Michael"}, "item 7", "item 8"}, 999}
flattenList(deep)
NG
_______________________________________________
Do not post admin requests to the list. They will be ignored.
AppleScript-Users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
Archives: http://lists.apple.com/archives/applescript-users
This email sent to email@hidden