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
lambda() of item 3 of fns
|λ|() of item 3 of fns
end run
end run



on closure(x)
on closure(x)
script
script
on lambda()
on |λ|()
return x * x
x * x
end lambda
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


script closure
lambda() of (item 3 of (map(closure, range(1, 10))))
on |λ|(x)
script
end run
on |λ|()
x * x
end |λ|
end script
end |λ|
end script


|λ|() of (item 3 of (map(closure, enumFromTo(1, 10))))
on closure(x)
script
on lambda()
return x * x
end lambda
end script
end closure




-- GENERIC FUNCTIONS ----------------------------------------------------------


-- enumFromTo :: Int -> Int -> [Int]
-- GENERIC FUNCTIONS
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo


-- map :: (a -> b) -> [a] -> [b]
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
on map(f, xs)
script mf
tell mReturn(f)
property lambda : f
set lng to length of xs
end script
set lst to {}
repeat with i from 1 to lng
set lng to length of xs
set lst to {}
set end of lst to |λ|(item i of xs, i, xs)
repeat with i from 1 to lng
end repeat
set end of lst to mf's lambda(item i of xs, i, xs)
return lst
end repeat
end tell
return lst
end map
end map


-- Lift 2nd class handler function into 1st class script wrapper

-- range :: Int -> Int -> Int
-- mReturn :: Handler -> Script
on range(m, n)
on mReturn(f)
set lng to (n - m) + 1
if class of f is script then
set base to m - 1
f
set lst to {}
else
repeat with i from 1 to lng
script
set end of lst to i + base
property |λ| : f
end repeat
end script
return lst
end if
end range
end mReturn</lang>

</lang>

{{Out}}
{{Out}}

<pre>9</pre>
<pre>9</pre>