Apply a callback to an array: Difference between revisions
Content added Content deleted
Line 170: | Line 170: | ||
For a more general implementation of '''map(list, function)''' |
For a more general implementation of '''map(list, function)''', '''reduce(list, function, startValue)''', and '''filter(list, predicate)''', we could write: |
||
<lang applescript>-- [a] -> (a -> b) -> [b] |
<lang applescript>-- [a] -> (a -> b) -> [b] |
||
Line 192: | Line 192: | ||
end repeat |
end repeat |
||
end reduce |
end reduce |
||
-- [a] -> (a -> Bool) -> [a] |
|||
on filter(xs, f) |
|||
set mf to mReturn(f) |
|||
set lst to {} |
|||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
set v to item i of xs |
|||
if mf's call(v, i, xs) then |
|||
set end of lst to v |
|||
end if |
|||
end repeat |
|||
return lst |
|||
end filter |
|||
-- An ordinary AppleScript handler function |
-- An ordinary AppleScript handler function |
||
Line 210: | Line 225: | ||
a + b |
a + b |
||
end sum |
end sum |
||
on isEven(n) |
|||
n mod 2 = 0 |
|||
end isEven |
|||
set |
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} |
||
{map( |
{map(xs, square), reduce(xs, sum, 0), filter(xs, isEven)}</lang> |
||
{{Out}} |
{{Out}} |
||
<pre>{{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, 55}</pre> |
<pre>{{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, 55, {2, 4, 6, 8, 10}}</pre> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |