RosettaCodeData/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript

60 lines
1.3 KiB
AppleScript
Raw Permalink Normal View History

2018-06-22 20:57:24 +00:00
-- ARITHMETIC GEOMETRIC MEAN -------------------------------------------------
2016-12-05 22:15:40 +01:00
property tolerance : 1.0E-5
-- agm :: Num a => a -> a -> a
on agm(a, g)
script withinTolerance
2018-06-22 20:57:24 +00:00
on |λ|(m)
2016-12-05 22:15:40 +01:00
tell m to ((its an) - (its gn)) < tolerance
2018-06-22 20:57:24 +00:00
end |λ|
2016-12-05 22:15:40 +01:00
end script
script nextRefinement
2018-06-22 20:57:24 +00:00
on |λ|(m)
2016-12-05 22:15:40 +01:00
tell m
set {an, gn} to {its an, its gn}
{an:(an + gn) / 2, gn:(an * gn) ^ 0.5}
end tell
2018-06-22 20:57:24 +00:00
end |λ|
2016-12-05 22:15:40 +01:00
end script
an of |until|(withinTolerance, ¬
nextRefinement, {an:(a + g) / 2, gn:(a * g) ^ 0.5})
end agm
2018-06-22 20:57:24 +00:00
-- TEST ----------------------------------------------------------------------
2016-12-05 22:15:40 +01:00
on run
agm(1, 1 / (2 ^ 0.5))
2018-06-22 20:57:24 +00:00
--> 0.847213084835
2016-12-05 22:15:40 +01:00
2018-06-22 20:57:24 +00:00
end run
2016-12-05 22:15:40 +01:00
2018-06-22 20:57:24 +00:00
-- GENERIC FUNCTIONS ---------------------------------------------------------
2016-12-05 22:15:40 +01:00
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set mp to mReturn(p)
2017-09-23 10:01:46 +02:00
set v to x
tell mReturn(f)
2018-06-22 20:57:24 +00:00
repeat until mp's |λ|(v)
set v to |λ|(v)
2017-09-23 10:01:46 +02:00
end repeat
end tell
return v
2016-12-05 22:15:40 +01:00
end |until|
-- 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
2018-06-22 20:57:24 +00:00
property |λ| : f
2016-12-05 22:15:40 +01:00
end script
end if
end mReturn