Jez Higgins

Freelance software grandad
software created
extended or repaired


Follow me on Mastodon
Applications, Libraries, Code
Talks & Presentations

Hire me
Contact

Older posts are available in the archive or through tags.

Feed

Friday 25 August 2017 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 JavaScriptism 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 this tweet, which is a Clojure version.

There has a couple of extra steps compared with my version, replacing empty strings to nils (which I now think might be unneccessary) and converting integers to their string representations, but the essential elements are 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.

(Of course with Clojure, being a Lisp, everything's inside out. Lispers' contend this is the correct and proper nature of things, but I've always struggled with it a bit. This example isn't so bad actually, but by the time you get to your fifth left bracket it can be really hard to navigate.)


Tagged code, rillet, javascript, and fp


Jez Higgins

Freelance software grandad
software created
extended or repaired

Follow me on Mastodon
Applications, Libraries, Code
Talks & Presentations

Hire me
Contact

Older posts are available in the archive or through tags.

Feed