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-18 23:37

I use closures in C all the time.  Also, typedefs are for pussies.


#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int (*mkadder(int n))(int i)
{
    static const unsigned char TEXT[13] = {
        0x55, 0x89, 0xe5, 0x8b, 0x45, 0x08, 0x5d, 0x05, 0, 0, 0, 0, 0xc3
    };
    unsigned char *p = malloc(13);
    if (!p) return NULL;
    memcpy(p, TEXT, 13);
    memcpy(p + 8, &n, 4);
    return (int (*)(int))p;
}

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