98 lines
2 KiB
AppleScript
98 lines
2 KiB
AppleScript
--------------- CALCULATING THE VALUE OF E ----------------
|
|
on run
|
|
|
|
sum(map(inverse, ¬
|
|
scanl(product, 1, enumFromTo(1, 16))))
|
|
|
|
--> 2.718281828459
|
|
|
|
end run
|
|
|
|
-- inverse :: Float -> Float
|
|
on inverse(x)
|
|
1 / x
|
|
end inverse
|
|
|
|
-- product :: Float -> Float -> Float
|
|
on product(a, b)
|
|
a * b
|
|
end product
|
|
|
|
|
|
--------------------- GENERIC FUNCTIONS ---------------------
|
|
|
|
-- enumFromTo :: Int -> Int -> [Int]
|
|
on enumFromTo(m, n)
|
|
if m ≤ n then
|
|
set lst to {}
|
|
repeat with i from m to n
|
|
set end of lst to i
|
|
end repeat
|
|
lst
|
|
else
|
|
{}
|
|
end if
|
|
end enumFromTo
|
|
|
|
-- 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
|
|
|
|
-- Lift 2nd class handler function into 1st class script wrapper
|
|
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
|
|
on mReturn(f)
|
|
if class of f is script then
|
|
f
|
|
else
|
|
script
|
|
property |λ| : f
|
|
end script
|
|
end if
|
|
end mReturn
|
|
|
|
-- map :: (a -> b) -> [a] -> [b]
|
|
on map(f, xs)
|
|
-- The list obtained by applying f
|
|
-- to each element of xs.
|
|
tell mReturn(f)
|
|
set lng to length of xs
|
|
set lst to {}
|
|
repeat with i from 1 to lng
|
|
set end of lst to |λ|(item i of xs, i, xs)
|
|
end repeat
|
|
return lst
|
|
end tell
|
|
end map
|
|
|
|
-- scanl :: (b -> a -> b) -> b -> [a] -> [b]
|
|
on scanl(f, startValue, xs)
|
|
tell mReturn(f)
|
|
set v to startValue
|
|
set lng to length of xs
|
|
set lst to {startValue}
|
|
repeat with i from 1 to lng
|
|
set v to |λ|(v, item i of xs, i, xs)
|
|
set end of lst to v
|
|
end repeat
|
|
return lst
|
|
end tell
|
|
end scanl
|
|
|
|
-- sum :: [Num] -> Num
|
|
on sum(xs)
|
|
script add
|
|
on |λ|(a, b)
|
|
a + b
|
|
end |λ|
|
|
end script
|
|
|
|
foldl(add, 0, xs)
|
|
end sum
|