Update all new Tasks
This commit is contained in:
parent
00a190b0a6
commit
91df62d461
5697 changed files with 93386 additions and 804 deletions
41
Task/Closures-Value-capture/C/closures-value-capture-1.c
Normal file
41
Task/Closures-Value-capture/C/closures-value-capture-1.c
Normal 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;
|
||||
}
|
||||
9
Task/Closures-Value-capture/C/closures-value-capture-2.c
Normal file
9
Task/Closures-Value-capture/C/closures-value-capture-2.c
Normal 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
|
||||
33
Task/Closures-Value-capture/C/closures-value-capture-3.c
Normal file
33
Task/Closures-Value-capture/C/closures-value-capture-3.c
Normal 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue