ãæ«å°¾æé©åããæ£ããç解ãã
以ä¸ã®è¨äºã§PythonãRubyã®æ«å°¾å帰é¢æ°ãã«ã¼ãã«å¤æããææ³ããæ«å°¾å帰æé©åãããæ«å°¾å¼ã³åºãæé©åãã¨ãã¦ç´¹ä»ããã¦ããã®ã§ããããããã®ç¨èªã使ãã®ã¯ééãã§ãã
ç´¹ä»ããã¦ããææ³(åçæç¸ãå©ç¨ãã¦å¶å¾¡ããã¼ãå¤å½¢ããææ³)èªä½ã¯å¤§å¤é¢ç½ãã§ããã
Pythonで末尾再帰最適化をする。
Rubyで末尾再帰最適化をする。
åèæç®ã¨ãã¦ä»¥ä¸ãæãã¦ããã¾ãã
William D. Clinger "Proper Tail Recursion and Space Efficiency"
ã¡ããã¨èªã¿ç´ãã¦ããªãã®ã§ã以ä¸ã®èª¬æã«ééããããããç¥ãã¾ããããã®å ´åã¯ãææãé¡ããã¾ãã
ã¾ããæ«å°¾å¼ã³åºã(Tail Call)ãã¯é¢æ°ã®ä¸çªæå¾ã®å¼(æ«å°¾å¼)ã§ãã£ã¦ãé¢æ°å¼ã³åºãã§ãããã®ãæãã¾ãã
void foo() { bar(); baz(); /* æ«å°¾å¼ã³åºã */ }
æ«å°¾å¼ã³åºãã¯å帰å¼ã³åºãã§ãªãã¦ãè¯ãã®ã§ãæ¬æ¥ã¯æ«å°¾å帰ããåºãæ¦å¿µã§ããããããæ«å°¾æé©åãå¿
è¦ã«ãªãã®ã¯ã»ã¨ãã©ã®å ´åå帰é¢æ°ãªã®ã§ã[è¨æ£]é¢æ°å¼ã³åºããå帰ãããå¦ããå¤æããäºã¯å°é£ã§ãã(ã³ã¼ã«ã°ã©ãã®æ§ç¯ãé£ãã)ãããæ«å°¾å¼ã³åºããç¡æ¡ä»¶ã§æ«å°¾å帰ã¨å¼ã¶ãã¨ãããããã§ãã
é¢æ°ãå¼ã³åºãéã«ã¯è²ã ãªç¨éã§ã¡ã¢ãªç¢ºä¿ãçºçãã¾ãã
- æ»ãå ã¢ãã¬ã¹ãã©ããã«ç©ã
- é¢æ°å¼æ°ã確ä¿ãã
- å¼ã³åºãå ã®ãã¼ã«ã«å¤æ°ãéé¿ãã
- å¼ã³åºãããé¢æ°ã®ãã¼ã«ã«å¤æ°ã確ä¿ãã
- ã¯ãã¼ã¸ã£ã®èªç±å¤æ°ã確ä¿ãã
çã§ãã
æ«å°¾å¼ã³åºãã®å ´åã¯ããããé¤å»ã§ããããã§ãããã©ãã»ã©å¹ççãªå®è£
ã«ãªã£ã¦ããããã£ã¦ããã¤ãã®ã¯ã©ã¹ã«åé¡ããã¾ãã
Improper Tail Recursionã¨Proper Tail Recursion
æ«å°¾å¼ã³åºãæã«æ»ãå
ã®ç¶ç¶ã渡ããããªå®è£
ãImproper(誤ã£ã) Tail Recursionãçæããªãå®è£
ãProper(æ£ãã) Tail Recursionã¨è¨ãã¾ãããæ»ãå
ã®ç¶ç¶ãçæãã¦æ¸¡ããã¨ããã®ã¯ã大æµã®å®è£
ã§ã¯ç¾å¨ã®ç°å¢(ãã¼ã«ã«å¤æ°ç)ãä¿åããæ»ãå
ã¢ãã¬ã¹ãã¹ã¿ãã¯ã«ç©ã¿ãé¢æ°ãã³ã¼ã«ãã¦ãããªã¿ã¼ã³ãããããªãã®ãæãã¾ãã
Improper Tail Recursionã§ã¯ãç°å¢ã®ç¢ºä¿ãªã©ãããã工夫ãã¦0ã«ãã¦ãæ»ãã¢ãã¬ã¹ã¯é¤å»ã§ããªãã®ã§å¿
ãã¡ã¢ãªãå¢å ãããã¤ãã¡ã¢ãªã足ããªããªãã¾ãã
ä¸æ¹ã®Proper Tail Recursionã¯ç¾å¨ã®ç°å¢ãç ´æ£ããé¢æ°ã³ã¼ã«ã®ä»£ããã«ãã ã®ã¸ã£ã³ããè¡ããããªå®è£
ãæãã¾ãã
ãã®å ´åãä¸åã®ã¡ã¢ãªã®å¢å ãé²ããã¨ãã§ãã¾ãã
ããã«ç´°ããã¯ã©ã¹åãã«ã¤ãã¦ãããã£ã±ã«èª¬æãã¾ãã
Improper Tail Recursionã®ã¯ã©ã¹
- S-Stack
- ç°å¢ã®ä¸é¨ãã¹ã¿ãã¯ä¸ã«ç´æ¥ç¢ºä¿ããå®è£ ã
- S-GC
- ç°å¢ããã¼ãã«ç¢ºä¿ãããã¤ã³ã¿ä¸ã¤ãä¿åããå®è£ ããã®å ´åé¢æ°ã³ã¼ã«ããæ»ããã¨ããæ»ãã ãã¼ã¿ã¯GCã«ãã解æ¾ã§ããã®ã§ãS-Stackããã¡ã¢ãªå¹çãè¯ãã¯ã©ã¹ã§ãã
Proper Tail Recursionã®ã¯ã©ã¹
- S-Tail
- ä¸ã§æ¸ããProper Tail Recursionã®æä½éã®æ¡ä»¶ãæºãããå®è£ ã
- S-Evlis
- S-Tailã®æ¡ä»¶ã«å ãæ«å°¾å¼ã³åºããã¾ããã ç°å¢ã®éé¿ãé¤å»ããå®è£ ããã¼ãã«éé¿ãããç°å¢ã¯äºåº¦ã¨ã¢ã¯ã»ã¹ãããªãã®ã§ãé¤å»ã§ãã¾ãã
- S-Free
- S-Tailã®æ¡ä»¶ã«å ãã¯ãã¼ã¸ã£å¤æãç¨ããå®è£ ãç°å¢ã®éé¿ãæå°éã«ãªãã¾ãã
- S-SFS (Safe for Space)
- S-Freeã«å ããæ¡ä»¶åå²ãªã©ã§ãå¤æ°ã®çå解æã使ãæ¹æ³ãç°å¢ã®éé¿ãããã«æ¸ãã¾ãã
ãã¦ãä¸è¬çã«ã¯æ«å°¾å¼ã³åºããProper Tail Recursionã§å®è£
ããããã¨ãæ«å°¾æé©åãããã¨è¨ãã¾ãã
ä¸ã®PythonãRubyã®ä¾ã¯é¢æ°ã³ã¼ã«ãé¤å»ãã¦ããããã§ã¯ãªãã®ã§æ«å°¾æé©åã«ã¯è©²å½ãã¾ãããé¢æ°ã®å¼ã³åºãé¢ä¿ãæ¸ãæããå¥ç¨®ã®å¤æã«ãªãã¾ãã
å®éããã®æ¹æ³ã§ãæ«å°¾å帰é¢æ°ã§ããã°ã¹ã¿ãã¯ã®å¢å ãé²ãã¦ããããã§ãããf(),g(),h(),..ã¨ç°ãªãé¢æ°ã次ã
ã¨æ«å°¾å¼ã³åºããããããªå ´åã«ã¯ã¹ã¿ãã¯ã®å¢å ãæããäºã¯ã§ããªããªã©ã®ç¹ã§æ«å°¾æé©åã¨ã¯ç°ãªã£ã¦ãã¾ãã