Higher-order functions: Difference between revisions
m
→{{header|AppleScript}}: updated primitives, (and normalisation of indents in an earlier contribution, though it doesn't seem to run ...)
(→{{header|AutoHotkey}}: make it more straightforward) |
m (→{{header|AppleScript}}: updated primitives, (and normalisation of indents in an earlier contribution, though it doesn't seem to run ...)) |
||
Line 186:
-- with another handler (call).
on sing about topic by singer
end sing
-- Define a handler in a script object,
-- then pass the script object.
script cellos
end script
sing about "functional programming" by cellos
-- Pass a different handler. This one is a closure
-- that uses a variable (voice) from its context.
on hire for voice
end hire
sing about "closures" by (hire for "Pipe Organ")</lang>
Line 215:
<lang applescript>on run
-- PASSING FUNCTIONS AS ARGUMENTS TO
-- MAP, FOLD/REDUCE, AND FILTER, ACROSS A LIST
set lstRange to {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 222:
--> {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100}
--> 385
Line 250:
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to
end repeat
return lst
end map
Line 262 ⟶ 263:
-- each list element (from left-to-right) to reduce it
-- to a single return value
-- In some languages, like JavaScript, this is called reduce()
-- Arguments: function, initial value of accumulator, list
--
on
set v to startValue
set
repeat with i from 1 to lng▼
▲ repeat with i from 1 to lng
end repeat
▲ set v to mf's lambda(v, item i of xs, i, xs)
end
-- Sublist of those elements for which the predicate
-- function returns true
-- filter :: (a -> Bool) -> [a] -> [a]
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
set lst to {}
set
repeat with i from 1 to lng
▲ end repeat
end filter
Line 295 ⟶ 299:
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
▲ else
property lambda : f▼
▲ property lambda : f
end script
end if
end mReturn
Line 321 ⟶ 328:
on isEven(x)
x mod 2 = 0
end isEven</lang>
{{Out}}
<lang applescript>{{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}, {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {true, false, true, false, true, false, true, false, true, false, true}}</lang>
=={{header|ATS}}==
|