RosettaCodeData/Task/First-class-functions/AppleScript/first-class-functions-2.applescript

99 lines
2.1 KiB
AppleScript
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
on run
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
set fs to {sin_, cos_, cube_}
set afs to {asin_, acos_, croot_}
2016-12-05 22:15:40 +01:00
-- Form a list of three composed function objects,
-- and map testWithHalf() across the list to produce the results of
-- application of each composed function (base function composed with inverse) to 0.5
2017-09-23 10:01:46 +02:00
script testWithHalf
on |λ|(f)
mReturn(f)'s |λ|(0.5)
end |λ|
end script
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
map(testWithHalf, zipWith(mCompose, fs, afs))
2016-12-05 22:15:40 +01:00
--> {0.5, 0.5, 0.5}
end run
-- Simple composition of two unadorned handlers into
-- a method of a script object
on mCompose(f, g)
script
2017-09-23 10:01:46 +02:00
on |λ|(x)
mReturn(f)'s |λ|(mReturn(g)'s |λ|(x))
end |λ|
2016-12-05 22:15:40 +01:00
end script
end mCompose
-- 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
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
2017-09-23 10:01:46 +02:00
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
2016-12-05 22:15:40 +01:00
end zipWith
2017-09-23 10:01:46 +02:00
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
2016-12-05 22:15:40 +01:00
else
2017-09-23 10:01:46 +02:00
x
2016-12-05 22:15:40 +01:00
end if
2017-09-23 10:01:46 +02:00
end min
2016-12-05 22:15:40 +01:00
on sin:r
(do shell script "echo 's(" & r & ")' | bc -l") as real
end sin:
on cos:r
(do shell script "echo 'c(" & r & ")' | bc -l") as real
end cos:
on cube:x
x ^ 3
end cube:
on croot:x
x ^ (1 / 3)
end croot:
on asin:r
(do shell script "echo 'a(" & r & "/sqrt(1-" & r & "^2))' | bc -l") as real
end asin:
on acos:r
(do shell script "echo 'a(sqrt(1-" & r & "^2)/" & r & ")' | bc -l") as real
end acos: