FizzBuzz with Composition. In C.

Posted on April 25, 2014

Just for the heck of it. Nothing fancy, aside from mild cognitive dissonance.

Correction: The result was of course closer to composition than to continuations, as was pointed out to me by a colleague.

#include <stdio.h>
#include <string.h>

/* Copyright (c) 2014 Eugene Crosser.                                      */
/* License: CC0 (http://creativecommons.org/choose/zero/)                  */

/* Toungue in cheek "continuation passing" implementation of FizzBuzz      */
/* Inspired by this:                                                       */
/* http://themonadreader.files.wordpress.com/2014/04/fizzbuzz.pdf          */

/* With Strings and garbage collection we would have used strings objects. */
/* As we don't want to muddle the code with memory managenemt, we just use */
/* static buffers here. Make them long enogh for the longest output.       */
typedef struct {
	char value[16];
	char dflt[16];
} fbstate_t;

fbstate_t test(int what, int against, char *v, fbstate_t ost) {
	fbstate_t nst;

	if (what % against == 0) {
		strncpy(nst.value, v, sizeof(nst.value));
		strncat(nst.value, ost.value, sizeof(nst.value));
		nst.dflt[0] = '\0';
	} else {
		nst = ost;
	}
	return nst;
}

fbstate_t dflt(int what) {
	fbstate_t nst;

	nst.value[0] = '\0';
	snprintf(nst.dflt, sizeof(nst.dflt), "%d", what);
	return nst;
}

fbstate_t final(fbstate_t ost) {
	fbstate_t nst;

	strncat(nst.value, nst.dflt, sizeof(nst.value));
	nst.dflt[0] = '\0';
	return nst;
}

fbstate_t run(int what) {
	return final(
		test(what, 3, "Fizz",
		  test(what, 5, "Buzz",
		    dflt(what))));
}

int main(int argc, char *argv[]) {
	int i;

	for (i = 1; i <= 100; i++) {
		fbstate_t st = run(i);
		printf("%s\n", st.value);
	}
	return 0;
}