Skip to content

Instantly share code, notes, and snippets.

@nobsun
Created December 24, 2013 07:12
Show Gist options
  • Save nobsun/8109832 to your computer and use it in GitHub Desktop.
Save nobsun/8109832 to your computer and use it in GitHub Desktop.
Haskell コード片鑑賞:「再帰」編 ref: http://qiita.com/nobsun/items/6c2fa63f294dbd98d5cb
factorial :: Integer -> Integer
factorial (n+1) = (n+1) * factorial n
factorial 0 = 1
append :: [a] -> [a] -> [a]
append (x:xs) ys = x : append xs ys
append [] ys = ys
gappend :: ([a] -> [a] -> [a]) -> ([a] -> [a] -> [a])
gappend _ [] ys = ys
gappend f (x:xs) ys = x : f xs ys
append' :: [a] -> [a] -> [a]
append' = fix gappend
gfibs :: [Integer] -> [Integer]
gfibs f = 0:1:zipWith (+) f (tail f)
fibs' :: [Integer]
fibs' = fix gfibs
gpascal :: [[Integer]] -> [[Integer]]
gpascal f = [1]:[ zipWith (+) ([0]++p) (p++[0]) | p <- f ]
pascal' :: [[Integer]]
pascal' = fix gpascal
undefined' :: a
undefined' = fix id
fix :: (a -> a) -> a
fix f = f (fix f)
fibs :: [Integer]
fibs = 0:1:zipWith (+) fibs (tail fibs)
pascal :: [[Integer]]
pascal = [1]:[ zipWith (+) ([0]++p) (p++[0]) | p <- pascal ]
undefined :: a
undefined = undefined
gfactorial :: (Integer -> Integer) -> (Integer -> Integer)
gfactorial _ 0 = 1
gfactorial f (n+1) = (n+1) * f n
factorial' :: Integer -> Integer
factorial' = fix gfactorial
factorial' 0
==> {- factorial' の定義 -}
fix gfactorial 0
==> {- fix の定義 -}
(let x = gfactorial x in x) 0
==> {- x を展開 -}
gfactorial x 0
==> {- gfactorial の定義 -}
1
factorial' 1
==> {- factorial' の定義 -}
fix gfactorial 1
==> {- fix の定義 -}
(let x = gfactorial x in x) 0
==> {- let -}
let x = gfactorial x in x 0
==> {- x = gfactorial x -}
let x = gfactorial x in gfactorial x 1
==> {- x = gfactorial x -}
let x = gfactorial x in gfactorial (gfactorial x) 1
==> {- gfactorial の定義 -}
let x = gfactorial x in 1 * (gfactorial x 0)
==> {- gfactorial の定義 -}
let x = gfactorial x in 1 * 1
==> {- 算術演算 -}
1
factorial' 2
==> {- factorial' の定義 -}
fix gfactorial 2
==> {- fix の定義 -}
(let x = gfactorial x in x) 2
==> {- let -}
let x = gfactorial x in x 2
==> {- x = gfactorial x -}
let x = gfactroial x in gfactorial x 2
==> {- x = gfactorial x -}
let x = gfactorial x in gfactorial (gfactorial x) 2
==> {- gfactorial の定義 -}
let x = gfactorial x in 2 * (gfactorial x 1)
==> {- x = gfactorial x -}
let x = gfactorial x in 2 * (gfactorial (gfactorial x) 1)
==> {- gfactorial の定義 -}
let x = gfactorial x in 2 * (1 * gfactorial x 0)
==> {- gfactorial の定義 -}
let x = gfactorial x in 2 * (1 * 1)
==> {- 算術演算 -}
2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment