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

Common Lisp in C

Name: Anonymous 2012-10-03 17:23

Lets write Common Lisp functions in generic C code.


/* (map #'func array) => map(array,length_of_array,sizeof(array),function_pointer) */
void *map(void *base,size_t len,size_t elemnsize, void (*func)(void *,void *)) {
  void *b = malloc(elemsize*len);
  size_t i;
  for(i=0;i<len;++i){
    func(b+(elemsize*1),base);
    base += elemsize;
  }
  return b;
}

Name: Anonymous 2012-10-03 19:17

>>1,5
Here is a version that accepts any type of array provided by the user, if the user wants to use malloc it can and more importantly the user may do malloc and free on the same level also the user may use stack arrays like a normal human being, you also avoid casting away type information through void pointers and look, you may even use different types of arrays in it.

#include <stdio.h>

#define unary(arg, exp)                         \
  __extension__                                 \
  ({                                            \
    arg;                                        \
    __typeof__(exp) _unary (arg) {              \
      return exp;                               \
    } _unary;                                   \
  })

#define map(in, size, func, out)                \
  do {                                          \
    size_t _i;                                  \
                                                \
    for (_i = 0; _i < (size); _i++)             \
      (out)[_i] = func((in)[_i]);               \
  } while (0)

#define N 10

int main (void) {
  int i;
  int a[N];
  double b[N];

  for (i = 0; i < N; i++)
    a[i] = i;

  map(a, N, unary(int n, n*n), b);

  for (i = 0; i < N; i++)
    printf("%d -> %f\n", a[i], b[i]);

  return 0;
}

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