RosettaCodeData/Task/Perfect-numbers/AppleScript/perfect-numbers-1.applescript

109 lines
2.4 KiB
AppleScript
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
-- PERFECT NUMBERS -----------------------------------------------------------
2016-12-05 22:15:40 +01:00
-- perfect :: integer -> bool
on perfect(n)
-- isFactor :: integer -> bool
script isFactor
2017-09-23 10:01:46 +02:00
on |λ|(x)
2016-12-05 22:15:40 +01:00
n mod x = 0
2017-09-23 10:01:46 +02:00
end |λ|
2016-12-05 22:15:40 +01:00
end script
-- quotient :: number -> number
script quotient
2017-09-23 10:01:46 +02:00
on |λ|(x)
2016-12-05 22:15:40 +01:00
n / x
2017-09-23 10:01:46 +02:00
end |λ|
2016-12-05 22:15:40 +01:00
end script
-- sum :: number -> number -> number
script sum
2017-09-23 10:01:46 +02:00
on |λ|(a, b)
2016-12-05 22:15:40 +01:00
a + b
2017-09-23 10:01:46 +02:00
end |λ|
2016-12-05 22:15:40 +01:00
end script
-- Integer factors of n below the square root
2017-09-23 10:01:46 +02:00
set lows to filter(isFactor, enumFromTo(1, (n ^ (1 / 2)) as integer))
2016-12-05 22:15:40 +01:00
-- low and high factors (quotients of low factors) tested for perfection
(n > 1) and (foldl(sum, 0, (lows & map(quotient, lows))) / 2 = n)
end perfect
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
filter(perfect, enumFromTo(1, 10000))
2016-12-05 22:15:40 +01:00
--> {6, 28, 496, 8128}
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
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
2016-12-05 22:15:40 +01:00
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
2017-09-23 10:01:46 +02:00
if |λ|(v, i, xs) then set end of lst to v
2016-12-05 22:15:40 +01:00
end repeat
return lst
end tell
end filter
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
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 foldl
-- 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