Last active
August 29, 2015 14:21
-
-
Save pacak/3e889f74e9f3d3720c3c to your computer and use it in GitHub Desktop.
hylomorphism factorial, no external dependencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE TemplateHaskell, DeriveFunctor #-} | |
fact1 :: Integer -> Integer | |
fact1 n = product [1..n] | |
reduceProduct [] = [] | |
reduceProduct [x] = [x] | |
reduceProduct (a:b:xs) = (a*b) : reduceProduct xs | |
product' [] = 1 | |
product' [x] = x | |
product' xs = product' (reduceProduct xs) | |
fact2 :: Integer -> Integer | |
fact2 n = product' [1..n] | |
data BTreeF a = LfF Integer | TF a a deriving (Functor, Show) | |
hylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b | |
hylo f g = h where h = f . fmap h . g | |
fact3 :: Integer -> Integer | |
fact3 i = hylo cpsi apsi (1, i) | |
where | |
cpsi (LfF i) = i | |
cpsi (TF l r) = l * r | |
apsi (f, t) = if f >= t | |
then LfF f | |
else let r = (t + f) `div` 2 | |
in TF (f, r) (r+1, t) | |
main :: IO () | |
main = do | |
print $ fact3 100000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment