Rustãã¯ãã§Fizz Buzz
Rustã®ãã¯ãã§Fizz Buzzãæ¸ãã¦ã¿ãã
ãã®Fizz Buzzã¯ãã«ã¼ãã¨åæ°å¤å®ããã¯ãã§å¦çãã¦ããã10é²æ°ã¨ãã¦è¡¨ç¤ºããé¨åã¯ãã¯ãã§ã¯ãªãRustæ¬ä½ã«ä»»ãã¦ãããã
åä½ã®èª¬æ
Rustã® macro_rules!
ã§ã¡ã¿ããã°ã©ãã³ã°ãè¡ãå ´åããã¼ã¯ã³åä½ã§ã®å¦çãåºæ¬ã¨ãªãããã®ãã使ãããããã£ã¼ã¯åºæ¬çã« tt
ãããã£ã¼ã ãã§ããã tt
ãããã£ã¼ã¯ããã¼ã¯ã³ããªã¼(æ¬å¼§ä»¥å¤ã®ãã¼ã¯ã³ããæ¬å¼§ã§å²ã¾ããä»»æã®ãã¼ã¯ã³å)1åã«ãããããã
ä»ã®ãããã£ã¼ã使ãã¨ããã®é¨åã¯æ§æ解æããã¦ASTã«å¤æããããASTã«å¤æãããé¨åã¯åä¸ã®ãã¼ã¯ã³ã¨ã¿ãªããã¦ãã¾ãã macro_rules!
ããã¯éééçã«ããæ±ããªãã
macro_rules! fizzbuzz_cond {
...
}
ãã®ãã¯ãã¯ãç¹å®ã®2é²æ°ã«å¯¾ããFizzBuzzå¤å®ãå¼ã¶ãå¼æ°ã¯ã
- å ¥åãã2é²æ°ã®æ®ã (0,1ã®ãã¼ã¯ã³åã§è¡¨ç¾ããã大ããæ¡ããé çªã«æ¶è²»ãã)
- æ¶è²»ããé¨åã®mod 3 (1ã®åæ°ã§è¡¨ç¾ãã)
- æ¶è²»ããé¨åã®mod 5 (1ã®åæ°ã§è¡¨ç¾ãã)
- æ¶è²»ããé¨åãããããæ´æ°åã®å¼ (printããããã«ä½¿ã)
ã§ããããã®ãã¯ãã¯æ¬¡ã®ããã«åä½ããã
- mod 3ã¨mod 5ãããããé¨åã大ããããå ´åã¯ãåã£ã¦ããç´ãã
- ã¾ã å ¥åãæ®ã£ã¦ããã°ããããå¦çãããå¦çä¸ã®æ°ã2åãããã2åãã¦1ã足ãã
- å ¥åãæ®ã£ã¦ããªããã°ãprintãããããã®æãåºåããããã®ã¨ãmod 3ã¨mod 5ã«å¿ãã¦åå²ããã
macro_rules! fizzbuzz_rec {
...
}
ãã®ãã¯ãã¯ãæå®ãããç¯å²ã®FizzBuzzãå®è¡ãããå¼æ°ã¯ã
- éå§ä½ç½®ã¨çµäºä½ç½®ããããããåãæ¡æ°ã®2ã¤ã®2é²æ°ã
(0 1 1 0), (1 0 1 1)
ã®ãããªå¥ã ã®å½¢ã§ã¯ãªããæ¡ãã¨ã«zipãã((0, 1) (1, 0) (1, 1) (0, 1))
ã®ãããªå½¢ã§æã¤ãããã¯æ¡æ°ã®ä¸ä¸è´ã«ãããã¹ãé²ãã»ãã«éè¦ãªæå³ãããããã®æ¹æ³ã ã¨ãå ¨ã¦ã®æ¡ã0ã§ç½®ããããæä½ãããããã - 確å®ããé¨åã®2é²æ°ã
ã§ããã fizzbuzz_rec!
ã¯ã2é²æ°ã®æ¡ã®æ§é ã«ãã¨ã¥ãã¦å帰çã« fizzbuzz_rec!
ãå¼ã¶ããã®ãããªä»çµã¿ã«ãã¦ããã®ã¯ãããããã¨å帰深度ãlogã«æãããã¨ãã§ããããã§ããã
macro_rules! fizzbuzz {
...
}
ãã®ãã¯ãã¯ãåã« fizzbuzz_rec!
ãå¼ã³åºããã©ã¤ãã§ããã
Rustã«ããããã¯ãã¡ã¿ããã°ã©ãã³ã°ã®ç¹å¾´
å®ç¨çã«ã¯ãRustã®å®£è¨çãã¯ãã¯ãboilerplateçãªã³ã¼ãã大éã«ä½ãå¿ è¦ããããåå¤ç¸æ§ãé§ä½¿ãããããæ§æçã«çæããã»ãããã¾ãããå ´åã«ãå¼·åãªå¹æãçºæ®ããããããããã®Fizz Buzzã®ãããªä¾ã¯éã³ä»¥ä¸ã®æå³ã¯ãªãã
ãã¯ãã¡ã¿ããã°ã©ãã³ã°ããã¦ã¿ã¦ããã£ãå¼·ãå¶ç´ã¯ããã¯ãå¼ã³åºãã®çµæã®åå©ç¨ã®é£ããã§ããããã¯ãã®å ¥åããã¼ã¯ã³åã§ããã®ã«å¯¾ãã¦ããã¯ãã®åºåã¯æ½è±¡æ§ææ¨ã§ãããæ½è±¡æ§ææ¨ã¯ãã¼ã¯ã³åã¨ãã¦å解éã§ãããã®ã®ãåæ½è±¡æ§ææ¨ã¯åä¸ã®ãã¼ã¯ã³ã§ã©ããããã¦ãã¾ãã宣è¨çãã¯ãããã¯ééçã«ããåãæ±ããªããããã¯å®ç¨ä¸ã¯ã»ã¼åé¡ãªããããã¯ãã¡ã¿ããã°ã©ãã³ã°ã«ã¨ã£ã¦ã¯é大ãªéå£ã¨ãªããé¢æ°ã«ããããã°ã©ã ã®æ§é åã妨ãã¦ããããã§ãããããã«ããããã¯ãã¡ã¿ããã°ã©ãã³ã°ã§ã¯å®è³ªçã«ãæ«å°¾å帰çãªæ¹æ³ã§ããããã°ã©ã ãæ§é åã§ããªããã¨ã«ãªãã
ããã«å ãã¦ãRustã®ãã¯ãã¯å³ããå±é深度å¶éããã(crateã®å±æ§ã§æ¡å¼µã§ãã)ãå±é深度å¶éã¯é常ãä»åå®è£ ããããã«å帰深度ãlogã«æãããã¯ããã¯ãç¨ãã¦åé¿ãããã¨ãå¤ããããããRustãã¯ãã¡ã¿ããã°ã©ãã³ã°ã§ã¯æ«å°¾å帰çãªæ¸ãæ¹ããã§ããªãããããã®ãã¯ããã¯ãä¸è¬çã«ã¯ä½¿ããªãã¨èããããã
Rustã®ãã¯ãã¡ã¿ããã°ã©ãã³ã°ã¯ãCã®ããªããã»ããµã¡ã¿ããã°ã©ãã³ã°ã¨æ¯ã¹ã¦ãã決ãã¦èªç±åº¦ãé«ãã¨ã¯ãããªãã ãããããã¯ãã¡ããæªããã¨ã§ã¯ãªããã¡ã¿ããã°ã©ãã³ã°ã®å®¹æãã¯ãã³ã³ãã¤ã©ãã½ã¼ã¹ã³ã¼ã解æãã¼ã«ãªã©ã«ã¨ã£ã¦ã®æ±ããããã¨ãã¬ã¼ããªãã®é¢ä¿ã«ããããã§ãããRustã®ãã¯ãã¡ã¿ããã°ã©ãã³ã°ããã®ããã«é£ããã®ãã¾ããã®ãã¬ã¼ããªãã®çµæã ã¨èãããããã¾ããããããéã³ã¨ãã¦ã®ã¡ã¿ããã°ã©ãã³ã°ã¯ããã®ããã«å°ãé£ããããããé¢ç½ãã