Update all new Tasks

This commit is contained in:
Ingy döt Net 2015-02-20 09:02:09 -05:00
parent 00a190b0a6
commit 91df62d461
5697 changed files with 93386 additions and 804 deletions

View file

@ -0,0 +1,11 @@
'''Task:''' Create a list of 10 functions, in the simplest manner possible
(anonymous functions are encouraged), such that the function at index <math>i</math>
(you may choose to start <math>i</math> from either 0 or 1), when run,
should return the square of the index, that is, <math>i^2</math>.
Display the result of running any but the last function,
to demonstrate that the function indeed remembers its value.
'''Goal:''' To demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the ''value''
of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.

View file

@ -0,0 +1,11 @@
[1:10]PROC(BOOL)INT squares;
FOR i FROM 1 TO 10 DO
HEAP INT captured i := i;
squares[i] := ((REF INT by ref i, INT by val i,BOOL b)INT:(INT i = by ref i; (b|by ref i := 0); by val i*i))
(captured i, captured i,)
OD;
FOR i FROM 1 TO 8 DO print(squares[i](i MOD 2 = 0)) OD;
print(new line);
FOR i FROM 1 TO 10 DO print(squares[i](FALSE)) OD

View file

@ -0,0 +1,30 @@
with Ada.Text_IO;
procedure Value_Capture is
protected type Fun is -- declaration of the type of a protected object
entry Init(Index: Natural);
function Result return Natural;
private
N: Natural := 0;
end Fun;
protected body Fun is -- the implementation of a protected object
entry Init(Index: Natural) when N=0 is
begin -- after N has been set to a nonzero value, it cannot be changed any more
N := Index;
end Init;
function Result return Natural is (N*N);
end Fun;
A: array (1 .. 10) of Fun; -- an array holding 10 protected objects
begin
for I in A'Range loop -- initialize the protected objects
A(I).Init(I);
end loop;
for I in A'First .. A'Last-1 loop -- evaluate the functions, except for the last
Ada.Text_IO.Put(Integer'Image(A(I).Result));
end loop;
end Value_Capture;

View file

@ -0,0 +1,5 @@
)abbrev package TESTP TestPackage
TestPackage() : with
test: () -> List((()->Integer))
== add
test() == [(() +-> i^2) for i in 1..10]

View file

@ -0,0 +1 @@
[x() for x in test()]

View file

@ -0,0 +1,2 @@
[1,4,9,16,25,36,49,64,81,100]
Type: List(Integer)

View file

@ -0,0 +1,10 @@
((main {
{ iter
1 take bons 1 take
dup cp
{*} cp
3 take
append }
10 times
collect !
{eval %d nl <<} each }))

View file

@ -0,0 +1,10 @@
100
81
64
49
36
25
16
9
4
1

View file

@ -0,0 +1,8 @@
( -1:?i
& :?funcs
& whl
' ( 1+!i:<10:?i
& !funcs ()'(.$i^2):?funcs
)
& whl'(!funcs:%?func %?funcs&out$(!func$))
);

View file

@ -0,0 +1,12 @@
#include <iostream>
#include <functional>
#include <vector>
int main() {
std::vector<std::function<int()> > funcs;
for (int i = 0; i < 10; i++)
funcs.push_back([=]() { return i * i; });
for ( std::function<int( )> f : funcs )
std::cout << f( ) << std::endl ;
return 0;
}

View file

@ -0,0 +1,41 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
typedef int (*f_int)();
#define TAG 0xdeadbeef
int _tmpl() {
volatile int x = TAG;
return x * x;
}
#define PROT (PROT_EXEC | PROT_WRITE)
#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS)
f_int dupf(int v)
{
size_t len = (void*)dupf - (void*)_tmpl;
f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);
char *p;
if(ret == MAP_FAILED) {
perror("mmap");
exit(-1);
}
memcpy(ret, _tmpl, len);
for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)
if (*(int *)p == TAG) *(int *)p = v;
return ret;
}
int main()
{
f_int funcs[10];
int i;
for (i = 0; i < 10; i++) funcs[i] = dupf(i);
for (i = 0; i < 9; i++)
printf("func[%d]: %d\n", i, funcs[i]());
return 0;
}

View file

@ -0,0 +1,9 @@
func[0]: 0
func[1]: 1
func[2]: 4
func[3]: 9
func[4]: 16
func[5]: 25
func[6]: 36
func[7]: 49
func[8]: 64

View file

@ -0,0 +1,33 @@
void init(void)
{
t = intern(lit("t"));
x = intern(lit("x"));
}
val square(val env)
{
val xbind = assoc(env, x); /* look up binding of variable x in env */
val xval = cdr(xbind); /* value is the cdr of the binding cell */
return num(cnum(xval) * cnum(xval));
}
int main(void)
{
int i;
val funlist = nil, iter;
init();
for (i = 0; i < 10; i++) {
val closure_env = cons(cons(x, num(i)), nil);
funlist = cons(func_f0(closure_env, square), funlist);
}
for (iter = funlist; iter != nil; iter = cdr(iter)) {
val fun = car(iter);
val square = funcall(fun, nao);
printf("%d\n", cnum(square));
}
return 0;
}

View file

@ -0,0 +1,5 @@
# Generate an array of functions.
funcs = ( for i in [ 0...10 ] then do ( i ) -> -> i * i )
# Call each function to demonstrate value capture.
console.log func() for func in funcs

View file

@ -0,0 +1,9 @@
CL-USER> (defparameter alist
(loop for i from 1 to 10
collect (cons i (let ((i i))
(lambda () (* i i))))))
ALIST
CL-USER> (funcall (cdr (assoc 2 alist)))
4
CL-USER> (funcall (cdr (assoc 8 alist)))
64

View file

@ -0,0 +1,10 @@
import std.stdio;
void main() {
int delegate()[] funcs;
foreach (i; 0 .. 10)
funcs ~= (i => () => i ^^ 2)(i);
writeln(funcs[3]());
}

View file

@ -0,0 +1,5 @@
void main() {
import std.stdio, std.range, std.algorithm;
10.iota.map!(i => () => i ^^ 2).map!q{ a() }.writeln;
}

View file

@ -0,0 +1,19 @@
program Project1;
type
TFuncIntResult = reference to function : integer;
var
Funcs : array [0..9] of TFuncIntResult;
i : integer;
begin
// Create 10 anonymous functions
for i := Low(Funcs) to High(Funcs) do
Funcs[i] := function() : integer begin Result := i*i; end;
// call all 10 functions
for i := Low(Funcs) to High(Funcs) do
writeln( Funcs[i]() );
end.

View file

@ -0,0 +1,6 @@
(require 'cl)
(mapcar 'funcall
(mapcar (lambda (x)
(lexical-let ((x x))
(lambda () (* x x)))) [1 2 3 4 5 6 7 8 9 10]))
;; => (1 4 9 16 25 36 49 64 81 100)

View file

@ -0,0 +1,13 @@
-module(capture_demo).
-export([demo/0]).
demo() ->
Funs = lists:map(fun (X) ->
fun () ->
X * X
end
end,
lists:seq(1,10)),
lists:foreach(fun (F) ->
io:fwrite("~B~n",[F()])
end, Funs).

View file

@ -0,0 +1,14 @@
USING: io kernel locals math prettyprint sequences ;
[let
! Create a sequence of 10 quotations
10 iota [
:> i ! Bind lexical variable i
[ i i * ] ! Push a quotation to calculate i squared
] map :> seq
{ 3 8 } [
dup pprint " squared is " write
seq nth call .
] each
]

View file

@ -0,0 +1,12 @@
USING: fry io kernel math prettyprint sequences ;
! Push a sequence of 10 quotations
10 iota [
'[ _ dup * ] ! Push a quotation ( i -- i*i )
] map
{ 3 8 } [
dup pprint " squared is " write
over nth call .
] each
drop

View file

@ -0,0 +1,17 @@
class Closures
{
Void main ()
{
// define a list of functions, which take no arguments and return an Int
|->Int|[] functions := [,]
// create and store a function which returns i*i for i in 0 to 10
(0..10).each |Int i|
{
functions.add (|->Int| { i*i })
}
// show result of calling function at index position 7
echo ("Function at index: " + 7 + " outputs " + functions[7].call)
}
}

View file

@ -0,0 +1,15 @@
package main
import "fmt"
func main() {
fs := make([]func() int, 10)
for i := range fs {
i := i
fs[i] = func() int {
return i * i
}
}
fmt.Println("func #0:", fs[0]())
fmt.Println("func #3:", fs[3]())
}

View file

@ -0,0 +1 @@
def closures = (0..9).collect{ i -> { -> i*i } }

View file

@ -0,0 +1,4 @@
assert closures instanceof List
assert closures.size() == 10
closures.each { assert it instanceof Closure }
println closures[7]()

View file

@ -0,0 +1 @@
fs = map (\i _ -> i * i) [1 .. 10]

View file

@ -0,0 +1 @@
fs = [const $ i * i | i <- [1 .. 10]]

View file

@ -0,0 +1 @@
fs = take 10 coFs where coFs = [const $ i * i | i <- [1 ..]]

View file

@ -0,0 +1,8 @@
> :t fs
fs :: [b -> Integer]
> map ($ ()) fs
[1,4,9,16,25,36,49,64,81,100]
> fs !! 9 $ ()
100
> fs !! 8 $ undefined
81

View file

@ -0,0 +1,15 @@
procedure main(args) # Closure/Variable Capture
every put(L := [], vcapture(1 to 10)) # build list of index closures
write("Randomly selecting L[",i := ?*L,"] = ",L[i]()) # L[i]() calls the closure
end
# The anonymous 'function', as a co-expression. Most of the code is standard
# boilerplate needed to use a co-expression as an anonymous function.
procedure vcapture(x) # vcapture closes over its argument
return makeProc { repeat { (x[1]^2) @ &source } }
end
procedure makeProc(A) # the makeProc PDCO from the UniLib Utils package
return (@A[1], A[1])
end

View file

@ -0,0 +1,3 @@
constF=:3 :0
{.''`(y "_)
)

View file

@ -0,0 +1,2 @@
flist=: constF"0 i.10
slist=: constF"0 *:i.10

View file

@ -0,0 +1,4 @@
flist @.3
3"_
slist @.3
9"_

View file

@ -0,0 +1,4 @@
flist @.4''
4
slist @.4''
16

View file

@ -0,0 +1,4 @@
flist@.(?9) ''
7
slist@.(?9) ''
25

View file

@ -0,0 +1,9 @@
( VL=. (<@:((<'"')(0:`)(,^:)&_))"0@:(^&2)@:i. 10 ) NB. Producing a list of boxed anonymous verbs (functions)
┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐
│0"_│1"_│4"_│9"_│16"_│25"_│36"_│49"_│64"_│81"_│
└───┴───┴───┴───┴────┴────┴────┴────┴────┴────┘
{::&VL 5 NB. Evoking the 6th verb (function)
25"_
{::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('')
25

View file

@ -0,0 +1,15 @@
import java.util.function.Supplier;
import java.util.ArrayList;
public class ValueCapture {
public static void main(String[] args) {
ArrayList<Supplier<Integer>> funcs = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int j = i;
funcs.add(() -> j * j);
}
Supplier<Integer> foo = funcs.get(3);
System.out.println(foo.get()); // prints "9"
}
}

View file

@ -0,0 +1,17 @@
import java.util.List;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public interface ValueCapture {
public static void main(String... arguments) {
List<IntSupplier> closures = IntStream.rangeClosed(0, 10)
.<IntSupplier>mapToObj(i -> () -> i * i)
.collect(toList())
;
IntSupplier closure = closures.get(3);
System.out.println(closure.getAsInt()); // prints "9"
}
}

View file

@ -0,0 +1,7 @@
var funcs = [];
for (var i = 0; i < 10; i++) {
funcs.push( (function(i) {
return function() { return i * i; }
})(i) );
}
window.alert(funcs[3]()); // alerts "9"

View file

@ -0,0 +1,9 @@
<script type="application/javascript;version=1.7">
var funcs = [];
for (var i = 0; i < 10; i++) {
let (i = i) {
funcs.push( function() { return i * i; } );
}
}
window.alert(funcs[3]()); // alerts "9"
</script>

View file

@ -0,0 +1 @@
funcs = [ () -> i^2 for i = 1:10 ]

View file

@ -0,0 +1,15 @@
:- object(value_capture).
:- public(show/0).
show :-
integer::sequence(1, 10, List),
meta::map(create_closure, List, Closures),
meta::map(call_closure, List, Closures).
create_closure(Index, [Double]>>(Double is Index*Index)).
call_closure(Index, Closure) :-
call(Closure, Result),
write('Closure '), write(Index), write(' : '), write(Result), nl.
:- end_object.

View file

@ -0,0 +1,12 @@
| ?- value_capture::show.
Closure 1 : 1
Closure 2 : 4
Closure 3 : 9
Closure 4 : 16
Closure 5 : 25
Closure 6 : 36
Closure 7 : 49
Closure 8 : 64
Closure 9 : 81
Closure 10 : 100
yes

View file

@ -0,0 +1,6 @@
funcs={}
for i=1,10 do
table.insert(funcs, function() return i*i end)
end
funcs[2]()
funcs[3]()

View file

@ -0,0 +1,5 @@
> L := map( i -> (() -> i^2), [seq](1..10) ):
> seq( L[i](),i=1..10);
1, 4, 9, 16, 25, 36, 49, 64, 81, 100
> L[4]();
16

View file

@ -0,0 +1,5 @@
Function[i, i^2 &] /@ Range@10
->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &}
%[[2]][]
->4

View file

@ -0,0 +1,13 @@
using System.Console;
module Closures
{
Main() : void
{
def f(x) { fun() { x ** 2 } }
def funcs = $[f(x) | x in $[0 .. 10]].ToArray(); // using array for easy indexing
WriteLine($"$(funcs[4]())");
WriteLine($"$(funcs[2]())");
}
}

View file

@ -0,0 +1,7 @@
let () =
let cls = Array.init 10 (fun i -> (function () -> i * i)) in
Random.self_init ();
for i = 1 to 6 do
let x = Random.int 9 in
Printf.printf " fun.(%d) = %d\n" x (cls.(x) ());
done

View file

@ -0,0 +1,7 @@
NSMutableArray *funcs = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
[funcs addObject:[^ { return i * i; } copy]];
}
int (^foo)(void) = funcs[3];
NSLog(@"%d", foo()); // logs "9"

View file

@ -0,0 +1 @@
vector(10,i,()->i^2)[5]()

View file

@ -0,0 +1,7 @@
<?php
$funcs = array();
for ($i = 0; $i < 10; $i++) {
$funcs[] = function () use ($i) { return $i * $i; };
}
echo $funcs[3](), "\n"; // prints 9
?>

View file

@ -0,0 +1,7 @@
<?php
$funcs = array();
for ($i = 0; $i < 10; $i++) {
$funcs[] = create_function('', '$i = ' . var_export($i, true) . '; return $i * $i;');
}
echo $funcs[3](), "\n"; // prints 9
?>

View file

@ -0,0 +1,5 @@
my @c = gather for ^10 -> $i {
take { $i * $i }
}
.().say for @c.pick(*); # call them in random order

View file

@ -0,0 +1 @@
say .() for pick *, map -> $i { -> {$i * $i} }, ^10

View file

@ -0,0 +1,2 @@
my @f = map(sub { $_ * $_ }, 0 .. 9); # @f is an array of subs
print $f[$_](), "\n" for (0 .. 8); # call and print all but last

View file

@ -0,0 +1,4 @@
(setq FunList
(make
(for @N 10
(link (curry (@N) () (* @N @N))) ) ) )

View file

@ -0,0 +1,13 @@
array funcs = ({});
foreach(enumerate(10);; int i)
{
funcs+= ({
lambda(int j)
{
return lambda()
{
return j*j;
};
}(i)
});
}

View file

@ -0,0 +1,14 @@
:-use_module(library(lambda)).
closure :-
numlist(1,10, Lnum),
maplist(make_func, Lnum, Lfunc),
maplist(call_func, Lnum, Lfunc).
make_func(I, \X^(X is I*I)).
call_func(N, F) :-
call(F, R),
format('Func ~w : ~w~n', [N, R]).

View file

@ -0,0 +1,4 @@
funcs = []
for i in range(10):
funcs.append(lambda: i * i)
print funcs[3]() # prints 81

View file

@ -0,0 +1,4 @@
funcs = []
for i in range(10):
funcs.append(lambda i=i: i * i)
print funcs[3]() # prints 9

View file

@ -0,0 +1,2 @@
funcs = [lambda i=i: i * i for i in range(10)]
print funcs[3]() # prints 9

View file

@ -0,0 +1,4 @@
funcs = []
for i in range(10):
funcs.append((lambda i: lambda: i * i)(i))
print funcs[3]() # prints 9

View file

@ -0,0 +1,2 @@
funcs = [(lambda i: lambda: i)(i * i) for i in range(10)]
print funcs[3]() # prints 9

View file

@ -0,0 +1,2 @@
funcs = map(lambda i: lambda: i * i, range(10))
print funcs[3]() # prints 9

View file

@ -0,0 +1,2 @@
funcs=[eval("lambda:%s"%i**2)for i in range(10)]
print funcs[3]() # prints 9

View file

@ -0,0 +1,9 @@
# assign 's' a list of ten functions
s <- sapply (1:10, # integers 1..10 become argument 'x' below
function (x) {
x # force evaluation of promise x
function (i=x) i*i # this *function* is the return value
})
s[[5]]() # call the fifth function in the list of returned functions
[1] 25 # returns vector of length 1 with the value 25

View file

@ -0,0 +1,2 @@
s[[5]](10)
[1] 100

View file

@ -0,0 +1,18 @@
s <- sapply (1:10,
function (x) {
x # force evaluation of promise x
function () {
R <- x*x
# evaluate the language expression "x <- x + 1" in the persistent parent environment
evalq (x <- x + 1, parent.env(environment()))
R # return squared value
}})
s[[5]]()
[1] 25 # 5^2
s[[5]]()
[1] 36 # now 6^2
s[[1]]()
[1] 1 # 1^2
s[[1]]()
[1] 4 # now 2^2

View file

@ -0,0 +1 @@
Data source: http://rosettacode.org/wiki/Closures/Value_capture

View file

@ -0,0 +1,14 @@
/*REXX pgm has a list of 10 functions, each returns its invocation(idx)²*/
do j=1 for 9 /*invoke random functions 9 times.*/
interpret 'CALL .'random(0,9) /*invoke a randomly selected func.*/
end /*j*/ /* [↑] the random func has no args*/
say 'The tenth invocation of .0 ' .0()
exit /*stick a fork in it, we're done.*/
/*─────────────────────────────────list of 10 functions─────────────────*/
/*[Below is the closest thing to anonymous functions in the REXX lang.] */
.0:return .(); .1:return .(); .2:return .(); .3:return .(); .4:return .()
.5:return .(); .6:return .(); .7:return .(); .8:return .(); .9:return .()
/*─────────────────────────────────. function───────────────────────────*/
.: if symbol('@')=='LIT' then @=0 /*handle 1st invoke*/; @=@+1; return @*@

View file

@ -0,0 +1,3 @@
#lang racket
(map (λ(f) (f))
(for/list ([i 10]) (λ () (* i i))))

View file

@ -0,0 +1 @@
'(0 1 4 9 16 25 36 49 64 81)

View file

@ -0,0 +1,6 @@
list = {}
(1..10).each {|i| list[i] = proc {i * i}}
p list[3].call #=> 9
p list[7][] #=> 49
i = 5
p list[3].call #=> 9

View file

@ -0,0 +1,5 @@
list = {}
for i in 1..10 do list[i] = proc {i * i} end
p list[3][] #=> 100
i = 5
p list[3][] #=> 25

View file

@ -0,0 +1,4 @@
fn main() {
let fs: ~[proc() -> uint] = range(0u,10).map(|i| {proc() i*i}).collect();
println!("7th val: {}", fs[7]());
}

View file

@ -0,0 +1,3 @@
val closures=for(i <- 0 to 9) yield (()=>i*i)
0 to 8 foreach (i=> println(closures(i)()))
println("---\n"+closures(7)())

View file

@ -0,0 +1,11 @@
;;; Collecting lambdas in a tail-recursive function.
(define (build-list-of-functions n i list)
(if (< i n)
(build-list-of-functions n (+ i 1) (cons (lambda () (* (- n i) (- n i))) list))
list))
(define list-of-functions (build-list-of-functions 11 1 '()))
(map (lambda (f) (f)) list-of-functions)
((list-ref list-of-functions 8))

View file

@ -0,0 +1,2 @@
(1 4 9 16 25 36 49 64 81 100)
81

View file

@ -0,0 +1,2 @@
funcs := (1 to: 10) collect: [ :i | [ i * i ] ] .
(funcs at: 3) value displayNl .

View file

@ -0,0 +1,36 @@
package require Tcl 8.6; # Just for tailcall command
# Builds a value-capturing closure; does NOT couple variables
proc closure {script} {
set valuemap {}
foreach v [uplevel 1 {info vars}] {
lappend valuemap [list $v [uplevel 1 [list set $v]]]
}
set body [list $valuemap $script [uplevel 1 {namespace current}]]
# Wrap, to stop untoward argument passing
return [list apply [list {} [list tailcall apply $body]]]
# A version of the previous line compatible with Tcl 8.5 would be this
# code, but the closure generated is more fragile:
### return [list apply $body]
}
# Simple helper, to avoid capturing unwanted variable
proc collectFor {var from to body} {
upvar 1 $var v
set result {}
for {set v $from} {$v < $to} {incr v} {lappend result [uplevel 1 $body]}
return $result
}
# Build a list of closures
proc buildList {} {
collectFor i 0 10 {
closure {
# This is the body of the closure
return [expr $i*$i]
}
}
}
set theClosures [buildList]
foreach i {a b c d e} {# Do 5 times; demonstrates no variable leakage
set idx [expr {int(rand()*9)}]; # pick random int from [0..9)
puts $idx=>[{*}[lindex $theClosures $idx]]
}