RosettaCodeData/Task/Flatten-a-list/AppleScript/flatten-a-list-2.applescript

44 lines
953 B
AppleScript
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
-- flatten :: Tree a -> [a]
on flatten(t)
if class of t is list then
concatMap(flatten, t)
2016-12-05 22:15:40 +01:00
else
2017-09-23 10:01:46 +02:00
t
2016-12-05 22:15:40 +01:00
end if
2017-09-23 10:01:46 +02:00
end flatten
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
-- TEST -----------------------------------------------------------------------
2016-12-05 22:15:40 +01:00
on run
2017-09-23 10:01:46 +02:00
flatten([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []])
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
--> {1, 2, 3, 4, 5, 6, 7, 8}
2016-12-05 22:15:40 +01:00
end run
2017-09-23 10:01:46 +02:00
-- GENERIC FUNCTIONS ----------------------------------------------------------
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lst to {}
set lng to length of xs
2016-12-05 22:15:40 +01:00
tell mReturn(f)
2017-09-23 10:01:46 +02:00
repeat with i from 1 to lng
set lst to (lst & |λ|(item i of xs, i, xs))
2016-12-05 22:15:40 +01:00
end repeat
end tell
2017-09-23 10:01:46 +02:00
return lst
end concatMap
2016-12-05 22:15:40 +01:00
-- 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
2017-09-23 10:01:46 +02:00
property |λ| : f
2016-12-05 22:15:40 +01:00
end script
end if
end mReturn