Skip to content

Instantly share code, notes, and snippets.

@edw
Created December 7, 2012 13:40
Show Gist options
  • Select an option

  • Save edw/4233337 to your computer and use it in GitHub Desktop.

Select an option

Save edw/4233337 to your computer and use it in GitHub Desktop.
Doubling an array, in a bunch of languages

Python

[2 * x for x in (1,2,3,4,5,6,7,8)]
# ==> [2, 4, 6, 8, 10, 12, 14, 16]

Clojure

(map #(* % 2) [1 2 3 4 5 6 7 8])
; ==> (2 4 6 8 10 12 14 16)

C

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

typedef int map_proc(int);

int *map(int c, int *xs, map_proc proc) {
  int *new_xs = malloc(sizeof(int) * c);
  for(int i = 0; i < c; i++) {
    new_xs[i] = proc(xs[i]);
  }
  return new_xs;
}

int *print_array(int c, int *xs) {
  putchar('[');
  for(int i = 0; i < c; i++) {
    if(i) {
      printf(" %d", xs[i]);
    } else {
      printf("%d", xs[i]);
    }
  }
  putchar(']');

  return xs;
};

int dubble(int x) {
  return 2 * x;
};

int main(int argc, char *argv[]) {
  int xs[] = {1, 2, 3, 4, 5, 6, 7, 8};
  int c = sizeof(xs) / sizeof(int);

  free(print_array(c, map(c, xs, dubble)));

  return EXIT_SUCCESS;
}

/*
    bash-3.2$ ./double
    [2 4 6 8 10 12 14 16]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment