September 2017 Update
This commit is contained in:
parent
bba7bfd280
commit
ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions
|
|
@ -1,15 +1,27 @@
|
|||
newtype Mu a = Roll { unroll :: Mu a -> a }
|
||||
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))
|
||||
fix = g <*> (Roll . g)
|
||||
where
|
||||
g = (. (>>= id) unroll)
|
||||
|
||||
fac :: Integer -> Integer
|
||||
fac = fix $ \f n -> if (n <= 0) then 1 else n * f (n-1)
|
||||
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
|
||||
fibs =
|
||||
fix $ (0 :) . (1 :) . (fix (\f (x:xs) (y:ys) -> x + y : f xs ys) <*> tail)
|
||||
|
||||
main = do
|
||||
print $ map fac [1 .. 20]
|
||||
print $ take 20 fibs
|
||||
main :: IO ()
|
||||
main =
|
||||
mapM_
|
||||
print
|
||||
[ map fac [1 .. 20]
|
||||
, take 20 fibs
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,28 +1,36 @@
|
|||
fix :: (a -> a) -> a
|
||||
fix f = f (fix f) -- _not_ the {fix f = x where x = f x}
|
||||
fix f = f (fix f) -- _not_ the {fix f = x where x = f x}
|
||||
|
||||
fac :: Integer -> Integer
|
||||
fac_ f n | n <= 0 = 1
|
||||
| otherwise = n * f (n-1)
|
||||
fac = fix fac_ -- fac_ (fac_ . fac_ . fac_ . fac_ . ...)
|
||||
fac_ f n
|
||||
| n <= 0 = 1
|
||||
| otherwise = n * f (n - 1)
|
||||
|
||||
fac = fix fac_ -- fac_ (fac_ . fac_ . fac_ . 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_ 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_ 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
|
||||
main : IO ()
|
||||
main =
|
||||
mapM_
|
||||
print
|
||||
[ map fac [1 .. 20]
|
||||
, map fib [0 .. 19]
|
||||
, take 20 fibs
|
||||
]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue