Recursively Extract Items from List of Lists

What’s an elegant way to extract every item from a list of lists of indeterminate depth?

For example, given.

set listOfLists to {{"blue", "red", {"shade", {"dark", "medium", "light"}}}, {"rough", {"nubbly", "raspy"}, {}}, "fabric"}

.I’d like to get.

set flatlist to set listOfLists to {"blue", "red", "shade", "dark", "medium", "light", "rough", "nubbly", "raspy", "fabric"}

I get vertigo every time I try to code a handler that calls itself and could use some guidance.

Thanks much,
Bryan

How about something like this (not recursive at all):


set listOfLists to {{"blue", "red", {"shade", {"dark", "medium", "light"}}}, {"rough", {"nubbly", "raspy"}, {}}, "fabric"}
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to space
set L to listOfLists as text
set AppleScript's text item delimiters to tid
set FL to words of L
FL --> {"blue", "red", "shade", "dark", "medium", "light", "rough", "nubbly", "raspy", "fabric"}

Neat! :slight_smile:

Here’s a recursive method, in case the list items aren’t necessarily text:

on flatten(listOfLists)
	script o
		property fl : {}
		
		on flttn(l)
			script p
				property lol : l
			end script
			
			repeat with i from 1 to (count l)
				set v to item i of p's lol
				if (v's class is list) then
					flttn(v)
				else
					set end of my fl to v
				end if
			end repeat
		end flttn
	end script
	
	tell o
		flttn(listOfLists)
		return its fl
	end tell
end flatten

set listOfLists to {{"blue", "red", {"shade", {"dark", "medium", "light"}}}, {"rough", {"nubbly", "raspy"}, {}}, "fabric"}
flatten(listOfLists)
1 Like

Also neat (and recursive!) :cool:

Woo hoo!

Thanks much - you guys are terrific. Problem solved & interesting things learned.

Happy happy,
Bryan