Apply a callback to an array: Difference between revisions

m
→‎{{header|AppleScript}}: Adjusted text, updated primitives
m (→‎{{header|AppleScript}}: Adjusted text, updated primitives)
Line 173:
 
 
For a more general implementation of '''map(listfunction, functionlist)''', '''reducefoldl(list, function, startValue, list)''', and '''filter(listpredicate, predicatelist)''', we could write:
 
<lang applescript>on run
Line 181:
{map(square, xs), ¬
filter(isEven, xs), ¬
reducefoldl(sum, 0, xs)}
--> {{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
 
-- sum :: Num -> Num -> Num
on sum(a, b)
a + b
end sum
 
-- isEven :: Int -> Bool
on isEven(n)
n mod 2 = 0
end isEven
 
 
-- GENERIC HIGHER ORDER FINCTIONS
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
set mf totell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to mf's lambda(item i of xs, i, xs)
end repeat
return lst
end repeattell
end map
 
-- reducefoldl :: (a -> b -> a) -> a -> [b] -> a
on reducefoldl(f, startValue, xs)
set mf totell mReturn(f)
set v to startValue
set vlng to startValuelength of xs
repeat with i from 1 to lng
set lng to length of xs
set v to mf's lambda(v, item i of xs, i, xs)
repeat with i from 1 to lng
end repeat
set v to mf's lambda(v, item i of xs, i, xs)
end repeat return v
returnend vtell
end reducefoldl
 
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
set mf totell mReturn(f)
set lst to {}
set lstlng to {}length of xs
repeat with i from 1 to lng
set lng to length of xs
repeat with i from 1 set v to lngitem i of xs
set v to item if lambda(v, i, xs) then set end of xslst to v
ifend mf's lambda(v, i, xs) thenrepeat
set end ofreturn lst to v
end iftell
end repeat
return lst
end filter
 
-- Lift 2nd class handler function lifted into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then return f
script f
else
property lambda : f
end script
property lambda : f
end mReturn
end script
</lang>
end if
end mReturn</lang>
 
{{Out}}
9,655

edits