[Haskell-cafe] Mysterious factorial
Ralf Hinze
ralf.hinze at comlab.ox.ac.uk
Wed Dec 30 12:35:48 EST 2009
As an aside, in one of my libraries I have a combinator
for folding a list in a binary-subdivision scheme.
> foldm :: (a -> a -> a) -> a -> [a] -> a
> foldm (*) e x
> | null x = e
> | otherwise = fst (rec (length x) x)
> where rec 1 (a : as) = (a, as)
> rec n as = (a1 * a2, as2)
> where m = n `div` 2
> (a1, as1) = rec (n - m) as
> (a2, as2) = rec m as1
Then factorial can be defined more succinctly
> factorial n = foldm (*) 1 [1 .. n]
Cheers, Ralf
More information about the Haskell-Cafe
mailing list