Monads in C pt. III

OK, the last C monad example:

typedef struct {
  char *string;
  int value;
} WriterInt;

WriterInt returnWriter(int i)
  WriterInt r;
  r.string = "";
  r.value = i;
  return r;

WriterInt bind(WriterInt (*f)(int),WriterInt x)
  WriterInt y = f(x.value);
  WriterInt z;
  z.value = y.value;
  int len = strlen(x.string)+strlen(y.string);
  z.string = malloc(len+1);
  return z;

WriterInt print(int i)
  WriterInt x;
  x.string = malloc(32);
  x.value = sprintf(x.string,"%d\n",i);
  return x;

WriterInt printplus_bad(int i)
  WriterInt x = print(i);
  return print(x.value); /* cheating! */

WriterInt printplus(int i)
  WriterInt x = print(i);
  return bind(print,x);

This time, instead of printing, we build up a string as a side effect. printplus() is implemented exactly as before, without knowledge of how to handle side effects, and yet it correctly handles strings returned as a side effect and concatenates them together. The magic is bind() which allows a function expecting an int input to be applied to a WriterInt.

I’m hoping that programmers of languages such as C can now begin to see the pattern shared by these examples.

Anyway, this is all just stalling for time while I try to get my quantum computation code working.


Post a Comment

Required fields are marked *

%d bloggers like this: