é 延è©ä¾¡ã§ã¯å帰ã®å¹çã¯ã©ããªããã¨ããåé¡ã§ããReal World Haskell ã§ãæ«å°¾å帰ã¯éè¦ã ã¨è¨ã£ãå¾ã«ãé 延è©ä¾¡ã§ã¯æ«å°¾å帰ãªãã¦æ°ã«ãããªã¨ã¡ãã¶å°ãè¿ãã¦ãã¾ãããããã haskell-cafeã§çããè¦ã¤ããã®ã§ãLuke Palmer ããã®è¨±å¯ãå¾ã¦è¨³ãå ¬éãã¾ãã
Luke Palmer ããã®èª¬æ
ç§ã Haskell ã§ããã°ã©ãã³ã°ããã¨ãã¯ãé常é¢æ°ãæ«å°¾å帰ã«ã¯ãã¾ããã(Int ã Bool ãªã©)æ£æ ¼ãªå¤ã¸ç³ã¿è¾¼ãå ´åãæ«å°¾å帰ã使ãã®ã¯ãããã¨ã§ããããã帰ç´çãªé 延æ§é ãä½æããå ´åãé¢ä¿ããç¨èªã¯ï¼ç§ã®è¨æ¶ãæ£ãããã°ï¼ãä½å帰ã(corecursion)ã§ãã(訳注ï¼mapã¯å帰ãã¤ä½å帰ã ããã§ãããå°éçãããã®ã§æ®éã®å帰ã§ããã¨æãã¾ã)ãæ«å°¾å帰ã¨ã¯ã¾ã£ããç°ãªãã¾ãã
ãªã¹ãã«å¯¾ãæ«å°¾å帰㧠map ããé¢æ°ãä¾ã¨ãã¦èãã¾ãããã
map f = go [] where go accum [] = accum go accum (x:xs) = go (accum ++ [f x]) xs
map f [1,2,3]ã¯ãä»ã®ãã¹ã¦ã®ãã¨ããå ã«ã次ã®ããã«ç³ã¿è¾¼ã¿ã¾ãã
map f [1,2,3] go [] [1,2,3] go ([] ++ [f 1]) [2,3] go (([] ++ [f 1]) ++ [f 2]) [3] go ((([] ++ [f 1]) ++ [f 2]) ++ [f 3]) [] (([] ++ [f 1]) ++ [f 2]) ++ [f 3]
ãããæ«å°¾å帰ãã¹ã¿ãã¯é åãç¯ç´ããã®ã§ããã°ãéã«ãã¼ãé åãæ¶è²»ãã¦ãã¾ãã§ããããï¼å ãã¦ããã®ããã« ++ ã使ãã¨ãäºä¹ã®ã³ã¹ãããããã¾ãããªããªãã++ ã®ã³ã¹ãã¯ãå·¦ã®å¼æ°ã®é·ãã«æ¯ä¾ããããã§ããï¼
ä½å帰(訳注ï¼æ®éã®å帰)㧠map ãæ¸ãã®ã¯ãããè¦ãããä¾ã§ãï¼
map f (x:xs) = f x : map f xs
å帰å¼ã³åºããã(:) ã®ä¸ã«ãããã¨ãåããã¾ããï¼æ°ããæ§é ã¯ãå¼æ°ã¨ãã¦æ¸¡ãããã®ã§ã¯ãªããå帰ã®å¤ã§æ§ç¯ããã¦ããã¾ããè¨ãæããã°ãå ¥åã®å ¨ä½ãè¦ãªãã¨ããããã¤ãã®åºåãçæãããã¨ãå¯è½ã§ããããã¯ãããæ§è³ªã§ãã
map f [1,2,3] f 1 : map f [2,3] -- ããã¦ããªã¹ãã®æ®ãã®è©ä¾¡ã«åããããã¨ãã« ... : f 2 : map f [3] -- ä¸ã«åã ... : f 3 : map f [] -- ä¸ã«åã ... : []
... ã¨ããè¨å·ã使ã£ãã®ã¯ããªã¹ãã®å é ãããå¿ãã¦ãã¾ã£ã¦ããããã¨ã強調ããããã§ãããªã¹ãã®æ®ããå¦çãã¦è¡ãã ãã§ããã®ã§ããããã§ããªã¹ãã®å é ã¯ååå¯è½ã§ãããã®æå³ã«ããã¦ãmap ã®ç©ºéã³ã¹ãã¯ä¸å®ã§ãã
ä½å帰ãå·§ã¿ã«ä½¿ã£ãããã°ã©ãã³ã°ã¯ãHaskell ã®æ¥½ãã¿ã®ä¸ã¤ã§ããããããããå½ä»¤åè¨èªãæ£æ ¼é¢æ°åè¨èªï¼ã¤ã¾ãä»ã®ã»ã¨ãã©ã®è¨èªï¼ã«æ £ãã¦ããã®ã§ããã°ããã¤ãæ´ãã®ã«æéããããã§ãããã