å㯠Haskell ãç¥ãã¾ã§ãå帰ã«é¢ãã¦ã¯ãããå¦ã¶ã¹ããã¨ã¯ãªãã¨æã£ã¦ãã¾ãããããããç¹°ãè¿ãããå帰ã§å®ç¾ããªããã°ãªããªãç´ç²é¢æ°åè¨èªã«è§¦ãã¦ã¯ããã¦ãå帰ã®æ·±æ·µãè¦ãæ°åã«ãªãã¾ããã
以ä¸ãProgramming in Haskell ãã 3 ã¤åé¡ãåºãã¾ããããªãã«ã¯ãå®è£ ã§ããã§ããããï¼
åé¡
以ä¸ã®é¢æ°ãå®è£ ããªããã
- ä¸ãããããªã¹ãã®ãã¹ã¦ã®é¨åãªã¹ããçæããé¢æ° subs
- 第ä¸å¼æ°ã第äºå¼æ°ã®ãªã¹ãã¸æ¿å ¥ãããã¹ã¦ã®ãªã¹ããçæããé¢æ° interleave
- ä¸ãããããªã¹ãã®é åãçæããé¢æ° perms
è¨èã ãã§ã¯ããåããªãã¨æãã¾ãã®ã§ãå®è¡ä¾ã示ãã¾ãã
subs [1,2,3] â [[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]] interleave 1 [2,3,4] â [[1,2,3,4],[2,1,3,4],[2,3,1,4],[2,3,4,1]] perms [1,2,3] â [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]
subs
subs ã«ä¸ãããªã¹ãã®å¤§ãããå¢ãããªãããå®è¡ãã¦ã¿ã¾ãããã
subs [] â [[]] subs [3] â [[],[3]] subs [2,3] â [[],[3],[2],[2,3]] subs [1,2,3] â [[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]
ããã§ãæå¾ã®å¼ã«ã¤ãã¦èãããã¨ã«ããx = 1ãxs = [2,3] ã¨ãã¾ãã
ãã¿ã¼ã³ããã観å¯ããã¨ãsubs [1,2,3] ã®çµæã®ååã¯ãsubs [2,3] ã«çããã¨æ°ä»ãã¾ããä¸ã¤åã®å¼ã§ãããããã㯠subs xs ã¨è¡¨ç¾ã§ããããã yss ã¨å¼ã¶ãã¨ã«ãã¾ãããã
ã¤ã¾ããHaskell ã§æ¸ãã¨ãããªãã¾ãã
subs (x:xs) = yss ++ å¾å where yss = subs xs
ãã¦å¾åã§ãããsubs [2,3] ããªãã¡ yss ã®åè¦ç´ ã« x ãã³ã³ã¹ããå½¢ã«ãªã£ã¦ãã¾ãããã£ã¦ subs ã¯ãããå®ç¾ã§ãã¾ãã
subs (x:xs) = yss ++ map (x:) yss where yss = subs xs
interleave
interleave ã«ä¸ãããªã¹ãã®å¤§ãããå¢ãããªãããå®è¡ãã¦ã¿ã¾ãããã
interleave 1 [] â [ [1]] interleave 1 [4] â [ [1,4], [4,1]] interleave 1 [3,4] â [ [1,3,4], [3,1,4], [3,4,1]] interleave 1 [2,3,4] â [[1,2,3,4],[2,1,3,4],[2,3,1,4],[2,3,4,1]]
ããã§ãæå¾ã®å¼ã«ã¤ãã¦èãããã¨ã«ããx = 1ãy = 2ãys = [3,4] ã¨ãã¾ãã
ãã¿ã¼ã³ããã観å¯ããã¨ãçµæã® tail ã¯ãinterleave 1 [3,4] ã« 2 ãã³ã³ã¹ãããã®ã«ãªã£ã¦ãã¾ããããªãã¡ãããæ¸ãã¾ãã
map (y:) (interleave x ys)
çµæã® head ã¯ãx:y:ys ã¨æ¸ãã¾ããããçµå±å ¨ä½ã¨ãã¦ããå®è£ ã§ãã¾ãã
interleave x (y:ys) = (x:y:ys) : map (y:) (interleave x ys)
perms
perms ã«ä¸ãããªã¹ãã®å¤§ãããå¢ãããªãããå®è¡ãã¦ã¿ã¾ãããã
perms [] â [[]] perms [3] â [[3]] perms [2,3] â [[2,3], [3,2]] perms [1,2,3] â [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]
ããã§ãæå¾ã®å¼ã«ã¤ãã¦èãããã¨ã«ããx = 1ãxs = [2,3] ã¨ãã¾ãããã¿ã¼ã³ããã観å¯ããã¨ãperms xs ã®åè¦ç´ ã«å¯¾ããx ã interleave ããã°ããã¨åãã¾ãã
ãã£ã¦ãããå®è£ ã§ãã¾ãã
perms (x:xs) = concatMap (interleave x) (perms xs)
é¢æ°ããã°ã©ãã³ã°
èè ã® Hutton ããã¯ããªãã¦é ããããã ã¨æã£ã¦ããããããã㯠"An introduction to functional programming" ããåã£ã¦ããé¢æ°ã ããã§ããæ¥æ¬èªè¨³ã¯ãé¢æ°ããã°ã©ãã³ã°ãã§ããã
ããããã°ãå¦çã®ã¨ãã«ãé¢æ°ããã°ã©ãã³ã°ãã輪è¬ã§èªã¿ã¾ãããå¦çã®ããã«ããããã追ãã¤ããã¨ãããã¨ãï¼ èªã¿è¿ãããããã©ãæ¬ã¯å®å®¶ã®æ®µãã¼ã«ã®ä¸ããªãããã