Skip to content

Instantly share code, notes, and snippets.

@dimitri
Created March 4, 2012 21:17
Show Gist options
  • Save dimitri/1974827 to your computer and use it in GitHub Desktop.
Save dimitri/1974827 to your computer and use it in GitHub Desktop.
FizzBuzz, in Emacs Lisp
;;; fizzbuzz.el --- FizzBuzz in Emacs Lisp
;;;
;;; Copyright 2012 Dimitri Fontaine
;;
;; This is using a simple trick: we build a list of entries then print them as-is,
;; so that we can manually add \n when necessary and append "fizz" and "buzz" on the
;; same line.
;;
;; This file has two implementations of fizzbuzz then a main routine (interactive) to
;; call to fill in a buffer. Try loading the file then M-x fizzbuzz.
;;
;; For another example of this kind see the Happy Numbers exercise, implemented both in
;; Emacs Lisp and in SQL here:
;;
;; http://tapoueh.org/blog/2010/08/30-happy-numbers.html
(require 'cl)
(defun fizzbuzz-loop (a b)
"Use loop from CL to list fizzbuzz"
(loop for i from a to b
if (zerop (mod i 3)) collect "fizz" and collect i into fizz
if (zerop (mod i 5)) collect "buzz" and collect i into buzz
unless (memq i (append fizz buzz)) collect (number-to-string i)
collect "\n"))
(defun fizzbuzz-dotimes (a b)
"Use dotimes to list fizzbuzz"
(let (fizzbuzz)
(dotimes (i (- b a))
(or (let ((f (when (zerop (mod (1+ i) 3)) (push "fizz" fizzbuzz)))
(b (when (zerop (mod (1+ i) 5)) (push "buzz" fizzbuzz))))
(or f b))
(push (number-to-string (1+ i)) fizzbuzz))
(push "\n" fizzbuzz))
(nreverse fizzbuzz)))
(defun fizzbuzz (&optional a b)
"return the fizz buzz string counting from a to b"
(interactive)
(let ((a (or a 1))
(b (or b 24)))
(with-current-buffer (get-buffer-create "*fizzbuzz*")
(erase-buffer)
(mapc 'insert (fizzbuzz-loop a b)))
;; (mapc 'insert (fizzbuzz-dotimes a b)))
(set-window-buffer (selected-window) "*fizzbuzz*")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment