RosettaCodeData/Task/Factorial/AppleScript/factorial-3.applescript

64 lines
1.3 KiB
AppleScript
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
-- FACTORIAL -----------------------------------------------------------------
2016-12-05 22:15:40 +01:00
-- factorial :: Int -> Int
on factorial(x)
script product
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
2017-09-23 10:01:46 +02:00
foldl(product, 1, enumFromTo(1, x))
2016-12-05 22:15:40 +01:00
end factorial
2017-09-23 10:01:46 +02:00
-- TEST ----------------------------------------------------------------------
2016-12-05 22:15:40 +01:00
on run
factorial(11)
--> 39916800
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
2016-12-05 22:15:40 +01:00
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
2017-09-23 10:01:46 +02:00
end enumFromTo
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
-- 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
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
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