RosettaCodeData/Task/Power-set/AppleScript/power-set-1.applescript

77 lines
1.8 KiB
AppleScript
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
-- POWER SET -----------------------------------------------------------------
2016-12-05 22:15:40 +01:00
-- powerset :: [a] -> [[a]]
on powerset(xs)
script subSet
2017-09-23 10:01:46 +02:00
on |λ|(acc, x)
script cons
on |λ|(y)
2016-12-05 22:15:40 +01:00
{x} & y
2017-09-23 10:01:46 +02:00
end |λ|
2016-12-05 22:15:40 +01:00
end script
2017-09-23 10:01:46 +02:00
acc & map(cons, acc)
end |λ|
2016-12-05 22:15:40 +01:00
end script
foldr(subSet, {{}}, xs)
end powerset
2017-09-23 10:01:46 +02:00
-- TEST ----------------------------------------------------------------------
2016-12-05 22:15:40 +01:00
on run
script test
2017-09-23 10:01:46 +02:00
on |λ|(x)
2016-12-05 22:15:40 +01:00
set {setName, setMembers} to x
{setName, powerset(setMembers)}
2017-09-23 10:01:46 +02:00
end |λ|
2016-12-05 22:15:40 +01:00
end script
map(test, [¬
["Set [1,2,3]", {1, 2, 3}], ¬
["Empty set", {}], ¬
["Set containing only empty set", {{}}]])
--> {{"Set [1,2,3]", {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}},
--> {"Empty set", {{}}},
--> {"Set containing only empty set", {{}, {{}}}}}
end run
2017-09-23 10:01:46 +02:00
-- GENERIC FUNCTIONS ---------------------------------------------------------
2016-12-05 22:15:40 +01:00
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
2017-09-23 10:01:46 +02:00
set v to |λ|(v, item i of xs, i, xs)
2016-12-05 22:15:40 +01:00
end repeat
return v
end tell
end foldr
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
2017-09-23 10:01:46 +02:00
set end of lst to |λ|(item i of xs, i, xs)
2016-12-05 22:15:40 +01:00
end repeat
return lst
end tell
end map
-- 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