/* CSE 333 Su12 Lecture 5 demo: funcparm.c */
/* Perkins */

/* Demonstrate use of function parameters.  This is a C version of */
/* a standard functional programming map function - c.f., CSE 341 */

/* same as funcparm.c except use a typedef for the function parameter */

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

// Define type PFII for pointer to int function returning int
typedef int (*PFII) (int);

// Print elements of a[0..len-1] with minimum of 4 spaces per number,
// right-justified.
void pr_array(int a[], int len) {
  int k;
  for (k = 0; k < len; k++)
    printf("%4d", a[k]);
  printf("\n");
}

// Simple functions from int->int to demonstrate map
int incr(int n) { return n+1; }
int dbl(int n)  { return n*2; }

// Replace each element x in a[0..len-1] by f(x)
void map(int a[], int len, PFII f) {
  int k;
  for (k = 0; k < len; k++)
    a[k] = (*f)(a[k]);          // a[k] = f(a[k]) works also
}

// Print an array, then transform it by incrementing and then doubling
// each element, printing the array after each transformation.
int main(int argc, char **argv) {
  const int size = 5;               // array size
  int nums[] = { 1, 3, 5, 7, 9 };

  // print original array
  pr_array(nums, size);

  // increment each element and print array
  map(nums, size, &incr);     // map(nums, size, incr) works also
  pr_array(nums, size);

  // double each element and print array
  map(nums, size, &dbl);      // map(nums, size, dbl) works also
  pr_array(nums, size);

  return EXIT_SUCCESS;
}