Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

PROGRAMMING CHALLENGE

Name: Anonymous 2010-07-16 18:57


This one should be difficult enough for you guys,

Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i.


My submission, in Scheme


(define (foo num)
  (lambda (x) (+ x num)))

Name: Anonymous 2010-07-19 4:48

Here's an "improved" C version, guaranteed to be portable across different Linux architectures.  It's also very easy to change the function to perform arbitrary computations.  With minimal modification it can also run on OS X.  No worries about the NX bit, either.  It does leak memory, though... like all good C programs should.


#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <err.h>
#include <unistd.h>

int (*mkadder(int n))(int i)
{
    FILE *tmp;
    void *lib, *func;
    int r;
    char nmc[20], nml[20], cmd[40];
    snprintf(nmc, sizeof(nmc), "./tmp%i.c", n);
    snprintf(nml, sizeof(nml), "./tmp%i.so", n);
    snprintf(cmd, sizeof(cmd), "gcc %s -shared -o %s", nmc, nml);
    if (!(tmp = fopen(nmc, "w"))) err(1, "fopen");
    fprintf(tmp, "int func(int i) { return i + %i; }\n", n);
    fclose(tmp);
    if ((r = system(cmd))) errx(1, "gcc");
    unlink(nmc);
    if (!(lib = dlopen(nml, RTLD_LAZY | RTLD_LOCAL)))
        errx(1, "dlopen: %s", dlerror());
    if (!(func = dlsym(lib, "func")))
        errx(1, "dlsym: %s", dlerror());
    unlink(nml);
    return func;
}

int main(int argc, char *argv[])
{
    int (*f)(int), (*g)(int);
    f = mkadder(10);
    g = mkadder(100);
    printf("f(5) = %i\n", f(5));
    printf("g(16) = %i\n", g(16));
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List