Lispè³ãªFizzBuzzãJavaScriptã§æ¸ãã¦ã¿ã
æè¿ãJavaScriptã«æ¹ãããçç±ã¯ãé¢æ°åè¨èªã®ç¹å¾´ãæã¤ã¨ããã«åå ããããããªæ°ããã¦ãã¾ãã
Lispãå¾æã¨ãã¦ãã人ã¯ãLispè³ãªãèãæ¹ãããã¨ã®ãã¨ã§ãã
èå³ã®æºæ³ã«åºä¼ãããã«ãLispè³ãè¦ãã¦ã¿ããã¨æãããèªã¿ãªãããJavaScriptã§Lispè³ãªFizzBuzz*1ãæ¸ãã¦ã¿ã¾ããã
ãææ¬
(for-each print (map (lambda (x) (cond ((= (modulo x 15) 0) "FizzBuzz") ((= (modulo x 5) 0) "Buzz") ((= (modulo x 3) 0) "Fizz") (else x))) (iota 100 1)))
ãããèªãã ãã§ã¯ãæ£ç´ä½ããã£ã¦ãããããã¾ããã次ã«ã解説ãèªã¿ãªããæ¸ãã¦ã¿ã¾ãã
ã¾ãã¯ãªã¹ããä½ã
ãã¨ãããã1ãã100ã¾ã§ã®ãªã¹ããä½ãã°è¯ãããã ã
Lispè³ãªäººã¯ããªã¹ããä¸å¿ã«ããã°ã©ã ãèããã¿ããã§ããã¾ãããã®çºæ³ãç§ã«ã¯ããã¾ããã
ãããJavaScriptã§æ¸ãã¦ã¿ã¾ããJavaScriptã«iotaãªãã¦é¢æ°ã¯ãªãã®ã§ãç¡åé¢æ°ã§ã*2
(function(max, start) { var list = []; for (var i = start; i <= max; i++) { list.push(i); } return list; })(100, 1)
mapé¢æ°ã§ãªã¹ããå å·¥ãã
ãmapã使ã£ã¦ãã®ãªã¹ããå å·¥ãã¦ãå¥ã®ãªã¹ããè¿ãã°ãããããã
mapé¢æ°ãJavaScriptã«ãªãã®ã§ãç¡åé¢æ°ã使ãã¾ãã
ããã®è¦ç´ ãç½®ãæãã¦ããã°ãåºåã¯å¾ããã©ãã«ã§ããªããããªããã
mapé¢æ°ã®æ©è½ãæã£ãç¡åé¢æ°ã使ã£ã¦ããã£ãä½ã£ããªã¹ããå å·¥ãã¾ããå ·ä½çã«ã¯ãä½ã£ããªã¹ãã®3ã®åæ°ã¨5ã®åæ°ã¨3ã¨5ã®ä¸¡æ¹ã®åæ°ã®ç®æãããããããFizzãBuzzãFizzBuzzã«ç½®ãæãã¾ãã
(function(func, list) { var clone = []; for (var i = 0; i < list.length; i++) { clone[i] = func(list[i]); } return clone; })(function(x) { if (x % 15 === 0) { x = 'FizzBuzz'; } else if (x % 5 === 0) { x = 'Buzz'; } else if (x % 3 === 0) { x = 'Fizz'; } return x; }, (function(max, start) { var list = []; for (var i = start; i <= max; i++) { list.push(i); } return list; })(100, 1));
åºåãèãã
ãããªã³ããã? 対話åã¤ã³ã¿ããªã¿ã§å®è¡ããã°çµæã®ãªã¹ãã¯ã¤ã³ã¿ããªã¿ãå°åãã¦ããããããªããã
ãã¾ãçµæã®ãªã¹ããprintãã¦ã¿ã¦ãè¯ããã
printã®ä»£ããã«ãããã°ã³ã³ã½ã¼ã«ã使ã£ã¦ãããã¨ãåæã§ãconsole.log() ã§åºåãã¦ã¿ã¾ãã
console.log((function(func, list) { var clone = []; for (var i = 0; i < list.length; i++) { clone[i] = func(list[i]); } return clone; })(function(x) { if (x % 15 === 0) { x = 'FizzBuzz'; } else if (x % 5 === 0) { x = 'Buzz'; } else if (x % 3 === 0) { x = 'Fizz'; } return x; }, (function(max, start) { var list = []; for (var i = start; i <= max; i++) { list.push(i); } return list; })(100, 1)));
è¦ç´ ãã¨ã«æ¹è¡ãã¦åºåãã
JavaScriptã¯ãfor-eachã使ããªãç°å¢ãå¤ãã£ã½ãã®ã§ããããç¡åé¢æ°ã§ã
(function(proc, list) { for (var i = 0; i < list.length; i++) { proc(list[i]); } })(function(x) { console.log(x); }, (function(func, list) { var clone = []; for (var i = 0; i < list.length; i++) { clone[i] = func(list[i]); } return clone; })(function(x) { if (x % 15 === 0) { x = 'FizzBuzz'; } else if (x % 5 === 0) { x = 'Buzz'; } else if (x % 3 === 0) { x = 'Fizz'; } return x; }, (function(max, start) { var list = []; for (var i = start; i <= max; i++) { list.push(i); } return list; })(100, 1)));
ãã¼ããç¡é§ã«ããããããåã£ã¦ããã©ãããããããªããã
ãã ããããã£ã¦ã²ã¨ã¤ã²ã¨ã¤ã®é¢æ°ã次ã®é¢æ°ã«æ¸¡ãã¦ããã¨ãé¢æ°ããã®ä¸çãæ¯é ãã¦ããæè¦ãå£éè¦ãããããªæ°ããã¾ããããã«ãã®çºæ³ãå½ããåã«ãªãã°ãç°¡æ½ã«æ¸ããLispã®ä½¿ãåæã¯ããªããªãè¯ãã®ãããããªãã¨ããæè¦ãæã¤ãã¨ãã§ãã¾ããã
ã¨ãããã¨ã§ãä»å¾ãé¢æ°åè¨èªã«å ¥éãã¦ã¿ã次第ã§ãã