Skip to content

Instantly share code, notes, and snippets.

@mahito1594
Last active August 27, 2022 10:28
Show Gist options
  • Save mahito1594/96762ad121cb2e7f86550fa69d250c85 to your computer and use it in GitHub Desktop.
Save mahito1594/96762ad121cb2e7f86550fa69d250c85 to your computer and use it in GitHub Desktop.
FizzBuzz with Emacs Lisp
;; Set max-lisp-eval-depth to some lower const, e.g., 600
(setq max-lisp-eval-depth 600)
(defun fizzbuzz--check (number)
"Check given number and then print Fizz / Buzz / FizzBuzz or itself."
(cond
((= (% number 15) 0) "FizzBuzz")
((= (% number 5) 0) "Buzz")
((= (% number 3) 0) "Fizz")
(t (number-to-string number))))
(defun fizzbuzz--recursive (lst)
"Simple fizzbuzz solution using recursive call."
(if lst
(cons (fizzbuzz--check (car lst))
(fizzbuzz--recursive (cdr lst)))
nil))
(defun fizzbuzz (limit)
(fizzbuzz--recursive (number-sequence 1 limit)))
;; When `fizzbuzz' is called with a number exceeding `max-lisp-eval-depth',
;; stack overflow occurs.
(fizzbuzz 601)
;; => Error (because `max-lisp-eval-depth' is set to 600)
;; Load tco.el to use tail call optimization.
;; See https://github.com/Wilfred/tco.el
;; Install via MELPA if necessary.
(require 'tco)
(defun-tco fizzbuzz--tailcall-optimized (lst accum)
"Fizz Buzz using tail call (Optimized).
`defun-tco' is the macro defined in tco.el"
(if (not lst)
accum
(fizzbuzz--tailcall-optimized (cdr lst)
(nconc accum
(list (fizzbuzz--check (car lst)))))))
(defun fizzbuzz-optimized (limit)
(fizzbuzz--tailcall-optimized (number-sequence 1 limit) nil))
(fizzbuzz-optimized 700)
;; => No error occurs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment