Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> In almost every other language this code would look messy or use some terrible recursion.

Nah, lots of other languages can do this.

Python:

    def factorial(i):
        return reduce(operator.mul, range(2, i+1), 1)
Ruby:

    def factorial(i)
        (2..i).reduce(1, :*)
    end
Haskell:

    factorial n = foldl (*) 1 [2..n]


For Python, we don't need to supply the optional initializer 1. And reduce resides in the functools namespace (much like mul is in operator). I assume we're not talking about that peculiar dialect of Python that is no longer supported a few months from now.


Not only that but in python 3.8, it can be written:

    def factorial(n):
        return math.prod(range(1,n+1))


Nice!


> For Python, we don't need to supply the optional initializer 1.

Without the initializer, factorial(0) doesn't work.


In haskell you can also use the `product` function:

    factorial n = product [1..n]




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: