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?
Although there is no C function defined specifically for computing factorials, C math library lets you compute gamma function.
The most basic way of defining a function in Haskell is to ``declare'' what it does. For example, we can write: double :: Int -> Int double n = 2*n. Here, the first line specifies the type of the function and the second line tells us how the output of double depends on its input.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With