Jump to content

Closures/Value capture: Difference between revisions

Line 1,349:
Or equivalently, using a more functional notation:
<lang perl6>say .() for pick *, map -> $i { -> {$i * $i} }, ^10</lang>
 
=={{header|Phix}}==
Phix does not support closures, but they seem easy enough to emulate
<lang Phix>-- First some generic handling stuff, handles partial_args
-- of any mixture of any length and element types.
sequence closures = {}
function add_closure(integer rid, sequence partial_args)
closures = append(closures,{rid,partial_args})
return length(closures) -- (return an integer id)
end function
 
function call_closure(integer id, sequence args)
{integer rid, sequence partial_args} = closures[id]
return call_func(rid,partial_args&args)
end function
 
-- The test routine to be made into a closure, or ten
-- Note that all external references/captured variables must
-- be passed as arguments, and grouped together on the lhs
function square(integer i)
return i*i
end function
 
-- Create the ten closures as asked for.
-- Here, cids is just {1,2,3,4,5,6,7,8,9,10}, however ids would be more
-- useful for a mixed bag of closures, possibly stored all over the shop.
-- Likewise add_closure could have been a procedure for this demo, but
-- you would probably want the function in a real-world application.
sequence cids = {}
for i=1 to 10 do
--for i=11 to 20 do -- alternative test
cids &= add_closure(routine_id("square"),{i})
end for
-- And finally call em (this loop is blissfully unaware what function
-- it is actually calling, and what partial_arguments it is passing)
for i=1 to 10 do
printf(1," %d",call_closure(cids[i],{}))
end for</lang>
{{out}}
<pre>
1 4 9 16 25 36 49 64 81 100
</pre>
output if that 11 to 20 add_closure loop is used instead:
<pre>
121 144 169 196 225 256 289 324 361 400
</pre>
Note however that any captured values are effectively immutable,
unless you also pass the id to the closure, and that in turn
does rude things to closures[id][2].
 
A dictionary based approach may prove somewhat easier:
<lang Phix>function square(integer tid)
integer i = getd("i",tid) -- (setd valid here too)
return i*i
end function
 
sequence tids = {}
for i=1 to 10 do
--for i=11 to 20 do
tids &= new_dict({{"i",i}})
end for
for i=1 to 10 do
printf(1," %d",square(tids[i]))
end for</lang>
same output, for both tests
 
=={{header|PHP}}==
7,820

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.