all tasks
This commit is contained in:
parent
b83f433714
commit
68f8f3e56b
14735 changed files with 178959 additions and 0 deletions
15
Task/Y-combinator/Haskell/y-combinator-1.hs
Normal file
15
Task/Y-combinator/Haskell/y-combinator-1.hs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
newtype Mu a = Roll { unroll :: Mu a -> a }
|
||||
|
||||
fix :: (a -> a) -> a
|
||||
fix = \f -> (\x -> f (unroll x x)) $ Roll (\x -> f (unroll x x))
|
||||
|
||||
fac :: Integer -> Integer
|
||||
fac = fix $ \f n -> if (n <= 0) then 1 else n * f (n-1)
|
||||
|
||||
fibs :: [Integer]
|
||||
fibs = fix $ \fbs -> 0 : 1 : fix zipP fbs (tail fbs)
|
||||
where zipP f (x:xs) (y:ys) = x+y : f xs ys
|
||||
|
||||
main = do
|
||||
print $ map fac [1 .. 20]
|
||||
print $ take 20 fibs
|
||||
28
Task/Y-combinator/Haskell/y-combinator-2.hs
Normal file
28
Task/Y-combinator/Haskell/y-combinator-2.hs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
fix :: (a -> a) -> a
|
||||
fix f = f (fix f)
|
||||
|
||||
fac :: Integer -> Integer
|
||||
fac' f n | n <= 0 = 1
|
||||
| otherwise = n * f (n-1)
|
||||
fac = fix fac'
|
||||
|
||||
-- a simple but wasteful exponential time definition:
|
||||
fib :: Integer -> Integer
|
||||
fib' f 0 = 0
|
||||
fib' f 1 = 1
|
||||
fib' f n = f (n-1) + f (n-2)
|
||||
fib = fix fib'
|
||||
|
||||
-- Or for far more efficiency, compute a lazy infinite list. This is
|
||||
-- a Y-combinator version of: fibs = 0:1:zipWith (+) fibs (tail fibs)
|
||||
fibs :: [Integer]
|
||||
fibs' a = 0:1:(fix zipP a (tail a))
|
||||
where
|
||||
zipP f (x:xs) (y:ys) = x+y : f xs ys
|
||||
fibs = fix fibs'
|
||||
|
||||
-- This code shows how the functions can be used:
|
||||
main = do
|
||||
print $ map fac [1 .. 20]
|
||||
print $ map fib [0 .. 19]
|
||||
print $ take 20 fibs
|
||||
Loading…
Add table
Add a link
Reference in a new issue