RosettaCodeData/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-3.applescript

62 lines
1.2 KiB
AppleScript
Raw Permalink Normal View History

2016-12-05 22:15:40 +01:00
-- fib :: Int -> Int
on fib(n)
2017-09-23 10:01:46 +02:00
-- lastTwo : (Int, Int) -> (Int, Int)
2016-12-05 22:15:40 +01:00
script lastTwo
2017-09-23 10:01:46 +02:00
on |λ|([a, b])
2016-12-05 22:15:40 +01:00
[b, 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
item 1 of foldl(lastTwo, {0, 1}, enumFromTo(1, n))
2016-12-05 22:15:40 +01:00
end fib
2017-09-23 10:01:46 +02:00
-- TEST -----------------------------------------------------------------------
2016-12-05 22:15:40 +01:00
on run
fib(32)
--> 2178309
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 n < m 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
-- 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
-- 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