Recursion Problem...

I need to turn this:

{{1, 2}, {3, 4}, {{5, 6}, {7, 8}, {9, 10}}, {{11, 12}, {{13, 14}, {15, 16}}}}

into this:

{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 14}, {15, 16}}

I know this can be done and I know it’s not hard, I just can’t get my head wrapped around the recursion process needed. Of note: the lists above are sample data only, the actual lists will contain many different classes. The lists WILL always be in pairs however (i.e. contain 2 items each) as shown in the second example.

Hi, Brad. Here’s one possible solution. I’ve used a script object in a handler because I personally don’t like using properties in the top level of a script if that can be avoided. But if you prefer, l and rec() can be brought out into the main script.

on listPairs(theList)
	script o
		property l : {}
		
		on rec(theList)
			repeat with i from 1 to (count theList)
				set thisItem to item i of theList
				if (count thisItem's lists) is 0 then
					set end of my l to thisItem
				else
					rec(thisItem)
				end if
			end repeat
		end rec
	end script
	
	o's rec(theList)
	return o's l
end listPairs

set theList to {{1, 2}, {3, 4}, {{5, 6}, {7, 8}, {9, 10}}, {{11, 12}, {{13, 14}, {15, 16}}}}
listPairs(theList)
--> {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 14}, {15, 16}}

Thanks Nigel,

My structure was close, but not working. As for where the properties are defined, I usually define properties at the top level if I want them to be available to all my handlers, otherwise – as long as it works I’m happy. :slight_smile:

Brad Bumgarner, CTA