Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 535
Simon Bergot Avatar asked Jul 24 '11 13:07

Simon Bergot


People also ask

Is there a built in function for factorial in C?

Although there is no C function defined specifically for computing factorials, C math library lets you compute gamma function.

How do you define a function in Haskell?

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.


1 Answers

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.

like image 142
hammar Avatar answered Oct 13 '22 19:10

hammar