haskellfactorial

Built-in factorial function in Haskell


I know this sounds like a stupid question, but here it is: Is there a built-in factorial in Haskell?

Google gives me tutorials about Haskell explaining how I can implement it myself, and I could not find anything on Hoogle. I don't want to rewrite it each time I need it.

I can use product [1..n] as a replacement, but is there a true Int -> Int factorial built-in function?


Solution

  • Even though it is commonly used for examples, the factorial function isn't all that useful in practice. The numbers grow very quickly, and most problems that include the factorial function can (and should) be computed in more efficient ways.

    A trivial example is computing binomial coefficients. While it is possible to define them as

    choose n k = factorial n `div` (factorial k * factorial (n-k))
    

    it is much more efficient not to use factorials:

    choose n 0 = 1
    choose 0 k = 0
    choose n k = choose (n-1) (k-1) * n `div` k 
    

    So, no, it's not included in the standard prelude. Neither is the Fibonacci sequence, the Ackermann function, or many other functions that while theoretically interesting are not used commonly enough in practice to warrant a spot in the standard libraries.

    That being said, there are many math libraries available on Hackage.