Functional Programming with Rillet: FizzBuzz

const rillet = require('./rillet.js');

const { of, zip, numbers } = rillet;

const fizzes = () => of('', '', 'Fizz').cycle();
const buzzes = () => of('', '', '', '', 'Buzz').cycle();
const words = () => zip(fizzes(), buzzes()).map(([f,b]) => `${f}${b}`)

const integers = () => numbers(1);

const fizzbuzz = (howMany) =>
        zip(words(), integers()).
        map(([w, n]) => w ? w : n).
        take(howMany);

fizzbuzz(100).forEach(console.log);

After writing about Eliza, I’m revisiting FizzBuzz, another programming classic. Functional style FizzBuzz are, when you first see one, a little bit vexing - where are the loops?, where’s all the if statements? - but that’s part of what’s makes them fun and interesting. What I’ve put together here in JavaScript using Rillet.js could have been written in pretty much any modern language and look pretty much the same. There’s only one real JavaScript_ism_ in the whole thing - w ? w : n - which selects a word or a number. Since empty strings in JavaScript are falsey (other, saner, languages disagree), we can use test it directly in the conditional rather than having to compare it with anything.

This little exercise was triggered by https://twitter.com/ostfale/status/894975530365333505[a tweet , now sadly lost, which was a Clojure version.

The original has a couple of extra steps compared with my version, replacing empty strings to nils (which I now think might be unnecessary) and converting integers to their string representations, but the essential elements were the same.

  • Create an infinite sequence with the word 'Fizz' every third item

  • Create another infinite sequence with the word 'Buzz' every fifth item

  • Merge those two sequences

  • Create a sequence of the natural numbers

  • Merge those two sequences, using the word if there is one, otherwise the number

  • Pull as many items out of the sequence as you want

  • FizzBuzz!

It’s actually a super neat and useful way to think about the problem.


Tagged code, rillet, javascript, and fp


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired



Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired