RosettaCodeData/Task/Apply-a-callback-to-an-array/AppleScript/apply-a-callback-to-an-array-2.applescript

79 lines
1.6 KiB
AppleScript
Raw Permalink Normal View History

2016-12-05 22:15:40 +01:00
on run
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{map(square, xs), ¬
2019-09-12 10:33:56 -07:00
filter(even, xs), ¬
foldl(add, 0, xs)}
2016-12-05 22:15:40 +01:00
--> {{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}
end run
-- square :: Num -> Num -> Num
on square(x)
x * x
end square
2019-09-12 10:33:56 -07:00
-- add :: Num -> Num -> Num
on add(a, b)
2016-12-05 22:15:40 +01:00
a + b
2019-09-12 10:33:56 -07:00
end add
2016-12-05 22:15:40 +01:00
2019-09-12 10:33:56 -07:00
-- even :: Int -> Bool
on even(x)
0 = x mod 2
end even
2016-12-05 22:15:40 +01:00
-- GENERIC HIGHER ORDER FUNCTIONS
2019-09-12 10:33:56 -07:00
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
2016-12-05 22:15:40 +01:00
tell mReturn(f)
set lst to {}
2019-09-12 10:33:56 -07:00
set lng to length of xs
2016-12-05 22:15:40 +01:00
repeat with i from 1 to lng
2019-09-12 10:33:56 -07:00
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
2016-12-05 22:15:40 +01:00
end repeat
return lst
end tell
2019-09-12 10:33:56 -07:00
end filter
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
2019-09-12 10:33:56 -07: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
2019-09-12 10:33:56 -07:00
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
2016-12-05 22:15:40 +01:00
on mReturn(f)
if class of f is script then
f
else
script
2019-09-12 10:33:56 -07:00
property |λ| : f
2016-12-05 22:15:40 +01:00
end script
end if
end mReturn
2019-09-12 10:33:56 -07:00
-- 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
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map