How to resolve the algorithm Flatten a list step by step in the AppleScript programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Flatten a list step by step in the AppleScript programming language
Table of Contents
Problem Statement
Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: Where the correct result would be the list:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Flatten a list step by step in the AppleScript programming language
Source code in the applescript programming language
my_flatten({{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}})
on my_flatten(aList)
if class of aList is not list then
return {aList}
else if length of aList is 0 then
return aList
else
return my_flatten(first item of aList) & (my_flatten(rest of aList))
end if
end my_flatten
-- flatten :: Tree a -> [a]
on flatten(t)
if class of t is list then
concatMap(flatten, t)
else
t
end if
end flatten
--------------------------- TEST ---------------------------
on run
flatten([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []])
--> {1, 2, 3, 4, 5, 6, 7, 8}
end run
-------------------- GENERIC FUNCTIONS ---------------------
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lst to {}
set lng to length of xs
tell mReturn(f)
repeat with i from 1 to lng
set lst to (lst & |λ|(item i of xs, i, xs))
end repeat
end tell
return lst
end concatMap
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
{1, 2, 3, 4, 5, 6, 7, 8}
on flatten(theList)
script o
property flatList : {}
-- Recursive handler dealing with the current (sub)list.
on flttn(thisList)
script p
property l : thisList
end script
repeat with i from 1 to (count thisList)
set thisItem to item i of p's l
if (thisItem's class is list) then
flttn(thisItem)
else
set end of my flatList to thisItem
end if
end repeat
end flttn
end script
if (theList's class is not list) then return theList
o's flttn(theList)
return o's flatList
end flatten
You may also check:How to resolve the algorithm Loops/Downward for step by step in the AppleScript programming language
You may also check:How to resolve the algorithm Odd word problem step by step in the Scheme programming language
You may also check:How to resolve the algorithm Doubly-linked list/Element insertion step by step in the OCaml programming language
You may also check:How to resolve the algorithm Loops/For with a specified step step by step in the Oz programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the NetRexx programming language