Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/6806946/built-in-factorial-function-in-haskell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...