Haskell ã®åªé ãã示ãããã«ãã使ãããã³ã¼ãã¯ãåªé ãã¨åãããããã ãã«ç¹åãã¦ãããç¾å®çã«ã¯é ããã¨ãå¤ããæ¸ãæã¯ä»ã«å¹çã®ããå®è£ ããããã¨ãç¥ã£ã¦ããã®ã ããã©ãèªã¿æã¯ããã§ã¯ãªããããå¾ã§å¹çãæªãã¨æ°ã¥ãã¦æç¶ã¨ããã¿ããã ã
ãã®è¨äºã§ã¯ãç¥è©±ã«ãªã£ã¦ããä¾ã3ã¤åãä¸ããå¹çã®ããå®è£ ã¨åããã¦ç´¹ä»ããããã® 3 ã¤ã®ä¾ã¨ã¯ã以ä¸ã®éãã
- ãã£ããããæ°
- ç´ æ°çæ
- ã½ã¼ã
ãã£ããããæ°
é 延è©ä¾¡ãæ´»ãããåªé ãªãã£ããããæ°ã®å®è£ ã¯ã以ä¸ã®éãã
fib n = fibs !! n fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
Haskellの「fib = 1:1:zipWith (+) fib (tail fib)」はとても遅いã«ãæ¸ããã¦ããããã«ããã®å®è£ ã¯é ãã
ãã®çç±ã¯ã(+) ã®è¨ç®ãé 延ãããã®å¾ æ©ãã¦ããè¨ç®ãæ¨ã¦ãããªãã®ã§ããªã¹ãã大ãããªãããã§ããã
a b c fibs = 0 : 1 : 0 + 1 : 1 + a : a + b : ...
a ã®è¨ç®ã¯é 延ããããb ã®è¨ç®ã«ä½¿ãããã®ã§æ¨ã¦ãããªããa ãæ¨ã¦ã¦ãªã¹ããé·ããªããªãããã«ããã«ã¯ã(+) ã®è¨ç®ãæ£æ ¼è©ä¾¡ãã¦ããã°ããããã®ããã«ã¯ãèªå㧠zipWith' ãå®è£ ããå¿ è¦ãããã
zipWith' f (a:as) (b:bs) = x `seq` x : zipWith' f as bs where x = f a b zipWith' _ _ _ = [] fib n = fibs !! n fibs = 0 : 1 : zipWith' (+) fibs (tail fibs)
é 延è©ä¾¡ç foldl ã«å¯¾ãã¦æ£æ ¼è©ä¾¡ç fold' ã¯ããã®ã«ãé 延è©ä¾¡ç zipWith ã«å¯¾ããæ£æ ¼è©ä¾¡ç zipWith' ãç¨æããã¦ãªãã®ã¯ãã©ããã¦ã ããï¼
ã¨ã«ããå¹çã®ããã³ã¼ãã示ãã«ã¯ããããã説æããªãã¨ãããªããªããããå¹çã¯æªããã©åªé ãªã³ã¼ãã示ããããªãæ°æã¡ãåãã£ã¦ããããã¨å¬ããã
ç´ æ°çæ
ããã¨ã©ãã¹ããã¹ã®ç¯©ã¨ç§°ãããã³ã¼ãã¯ä»¥ä¸ã®éãã
prime n = primes !! n primes = sieve [2..] sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
遅延評価によるエラトステネスの篩ã«æ¸ããã¦ããããã«ãå®ã¯ããã¯ã¨ã©ãã¹ããã¹ã®ç¯©ã§ã¯ãªãããªãã ããï¼ ã¨ã©ãã¹ããã¹ã®æ¹æ³ã§ããã¨ãã°5ã®åæ°ãæ¶ãã¨ãã5 ã®æ¬¡ã¯ 10 ã対象ã¨ããã7 ã¯ç¸æã«ããªãã(6ã8ã9 ã¯ãã§ã«æ¶ãã¦ãã)
ãããããã®ã³ã¼ãã§ã¯ 7 ã 5 ã§å²ã£ã¦ãã¾ããããã§ã¯èªå¤§åºåã¨è¨ããã¦ããããããªãã ããã
ãã®åé¡ãæ±ã£ãå¦è¡çãªè«æã¨ãã¦ã¯ãThe Genuine Sieve of Eratosthenesããããå®éåé¡ã¨ãã¦ãHaskellã§ç´ æ°ãå¿ è¦ã§ããã°ããã®è«æã®ä½è ãå®è£ ãã primes パッケージã使ããã
ã½ã¼ã
ãã¾ãã«ãæåãªã®ã¯ã以ä¸ã® quicksort ã ã
quicksort [] = [] quicksort (p:xs) = quicksort [ x | x <- xs, x <= p] ++ [p] ++ quicksort [ x | x <- xs, x > p]
ãããããã®ã³ã¼ãã¯ãpivot ã¨ãã¦ãªã¹ãã®å é ã使ã£ã¦ãããããæ´åããããªã¹ããã½ã¼ããããã¨ããã¨ãO(n^2) ã«ãªã£ã¦ãã¾ãã
Haskell 98 ã§ã¯ãsortBy ã O(n^2) ã®æ¿å ¥ã½ã¼ããã¦å®ç¾©ãã¦ããé©æãããããã実際の実装ã§ã¯ããã¼ã¸ã½ã¼ãã使ããã¦ããã
æ¨ãå©ç¨ãããã¼ãã½ã¼ãã¯関数プログラミングの楽しみã®ç´¹ä»è¨äºããé åãå©ç¨ãããã¼ãã½ã¼ããªãST で破壊的なヒープソートããé åãç¨ããã¯ã¤ãã¯ã½ã¼ãã¯Haskellの配列でクイックソートãåç §ã®ãã¨ã