Commits

Jesús Gómez  committed e029d36

C version

  • Participants
  • Parent commits 9760d53

Comments (0)

Files changed (1)

+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+
+double f(double);
+double f2(double);
+double f12(double);
+
+typedef double (*g)(double);
+
+typedef struct
+{
+  char **keys;
+  g *values;
+  int n;
+} map;
+
+void map_construct(map *, int, ...);
+g map_get(const map *, const char *);
+
+void map_construct(map *mapfun, int n, ...)
+{
+  va_list argp;
+  char *key;
+  g value;
+  int i;
+  mapfun->keys = (char **) malloc(n * sizeof(char *));
+  mapfun->values = (g*) malloc(n * sizeof(g));
+  mapfun->n = n;
+
+  va_start(argp, n);
+  for(i = 0; i < n; i++)
+    {
+      key = va_arg(argp, char*);
+      value = va_arg(argp, g);
+      mapfun->keys[i] = key;
+      mapfun->values[i] = value;
+    }
+  va_end(argp);
+}
+  
+g map_get(const map *mapfun, const char* key)
+{
+  int i;
+  for(i = 0; i < mapfun->n; i++)
+    if(!strcmp(mapfun->keys[i], key))
+      return mapfun->values[i];
+  return NULL;
+}
+
+double f(double x)
+{
+  return x;
+}
+
+double f2(double x)
+{
+  return x*x;
+}
+
+double f12(double x)
+{
+  return x/2;
+}
+
+int main(int argc, char **argv)
+{
+  char *fun = argv[1];
+  double x = strtod(argv[2], NULL);
+  map mapfun;
+  
+  map_construct(&mapfun, 3,
+		"f",   f,
+		"f2",  f2,
+		"f12", f12
+		);
+  printf("%f\n", map_get(&mapfun, fun)(x));
+}