Freelance software grandad
software created
extended or repaired
Follow me on Mastodon
Applications, Libraries, Code
Talks & Presentations
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 sameThe functional version of #fizzbuzz #lazyprogramming with @KevlinHenney pic.twitter.com/oUHjwWIiqE
— Uwe Sauerbrei (@ostfale) August 8, 2017
(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.)
Freelance software grandad
software created
extended or repaired
Follow me on Mastodon
Applications, Libraries, Code
Talks & Presentations