Closures/Value capture: Difference between revisions
Content added Content deleted
m (→{{header|Sidef}}: updated code) |
(→{{header|AppleScript}}: Updated primitives) |
||
Line 84: | Line 84: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
<lang AppleScript>on run |
<lang AppleScript>on run |
||
set fns to {} |
set fns to {} |
||
Line 94: | Line 92: | ||
end repeat |
end repeat |
||
|λ|() of item 3 of fns |
|||
⚫ | |||
end run |
end run |
||
on closure(x) |
on closure(x) |
||
script |
script |
||
on |
on |λ|() |
||
x * x |
|||
end |
end |λ| |
||
end script |
end script |
||
end closure</lang> |
end closure</lang> |
||
{{Out}} |
{{Out}} |
||
<pre>9</pre> |
<pre>9</pre> |
||
Or, in a more functional pattern of composition: |
Or, in a more functional pattern of composition: |
||
<lang AppleScript>-- CLOSURE -------------------------------------------------------------------- |
|||
<lang AppleScript>on run |
|||
⚫ | |||
⚫ | |||
on |λ|(x) |
|||
⚫ | |||
end run |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
end |λ| |
|||
end script |
|||
⚫ | |||
on closure(x) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
-- GENERIC FUNCTIONS ---------------------------------------------------------- |
|||
-- enumFromTo :: Int -> Int -> [Int] |
|||
-- GENERIC FUNCTIONS |
|||
on enumFromTo(m, n) |
|||
if n < m then |
|||
set d to -1 |
|||
⚫ | |||
set d to 1 |
|||
end if |
|||
⚫ | |||
repeat with i from m to n by d |
|||
set end of lst to i |
|||
end repeat |
|||
⚫ | |||
end enumFromTo |
|||
-- map :: (a -> b) -> [a] -> [b] |
-- map :: (a -> b) -> [a] -> [b] |
||
on map(f, xs) |
on map(f, xs) |
||
tell mReturn(f) |
|||
set lng to length of xs |
|||
set lst to {} |
|||
repeat with i from 1 to lng |
|||
⚫ | |||
set lst to |
set end of lst to |λ|(item i of xs, i, xs) |
||
end repeat |
|||
return lst |
|||
end |
end tell |
||
⚫ | |||
end map |
end map |
||
-- Lift 2nd class handler function into 1st class script wrapper |
|||
-- |
-- mReturn :: Handler -> Script |
||
on |
on mReturn(f) |
||
if class of f is script then |
|||
f |
|||
else |
|||
script |
|||
property |λ| : f |
|||
end |
end script |
||
end if |
|||
end |
end mReturn</lang> |
||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>9</pre> |
<pre>9</pre> |
||