2007/05/09

FizzBuzz

Erlang でやっておこう。


-module(a).
-compile(export_all).

m() ->
F = fun
(_, 0, 0) ->
"FizzBuzz";
(_, 0, _) ->
"Fizz";
(_, _, 0) ->
"Buzz";
(X, _, _) ->
integer_to_list(X)
end,
erlang:display([F(X, X rem 3, X rem 5) || X <- lists:seq(1, 100)]).


Common Lisp でも

(loop for i from 1 to 100
collect (cond ((zerop (rem i 15)) "FizzBuzz")
((zerop (rem i 5)) "Buzz")
((zerop (rem i 3)) "Fizz")
(t i)))

Common Lisp ならマクロで

(defmacro f (sym &rest args)
`(cond
((and ,@(mapcar #'(lambda (a)
`(zerop (rem i ,(car a))))
args)
,(format nil "~{~a~}" (mapcar #'cadr args))))
,@(mapcar #'(lambda (a)
`((zerop (rem i ,(car a))) ,(cadr a)))
args)
(t ,sym)))

(loop for i from 1 to 100
collect (f i (3 "Fizz") (5 "Buzz")))

(loop for i from 1 to 100
collect (f i (3 "Fizz") (5 "Buzz") (6 "Huzz")))


いずれも出力部は手をぬきました。

0 件のコメント: