Haskell程序崩溃 - 无限递归?错误的地方声明?

Sas*_*kia 4 recursion haskell where

我需要计算1..n中所有因子的乘积.当我将此函数称为double_factorial(至少有2或3作为args)时,它似乎被调用片刻,但没有任何反应,几秒钟后GHCi就会关闭.怎么了?是否有一些我无法看到的无限递归?这是我的代码:

double_factorial :: Integer->Integer
double_factorial n 
    | n<0 = error "negative number is given"
    | n==0 = 1
    | otherwise = (factorial n)*(double_factorial n-1)
    where
    factorial :: Integer->Integer
    factorial n 
        | n == 0  = 1
        | otherwise = n*(factorial n-1)
Run Code Online (Sandbox Code Playgroud)

Mar*_*Łoś 11

(double_factorial n-1)意思((double_factorial n) - 1)是,这是一个无限的递归问题.


Pau*_*ers 6

首先,因为你直接打开GHCi,GHCi停止运行后,它运行的终端窗口就会关闭.如果你打开cmd(或类似的终端),然后从那里使用GHCi,你可以看到GHCi停止运行时抛出的错误.在这种情况下,我们得到:

<interactive>: out of memory
Run Code Online (Sandbox Code Playgroud)

这确实表明了无限递归问题,正如您已经怀疑的那样.

因为factorial它是更简单的函数,所以更容易检查它的递归调用是否是罪魁祸首.它是factorial n - 1手段(factorial n) - 1而非手段factorial (n - 1).调用factorial n定义factorial n几乎就是无限递归的教科书案例.在double_factorial我们看到同样的问题.


Mih*_*eac 5

你有一个递归问题:f x - 1是不一样的f (x - 1).解决方案(删除不需要的括号并添加所需的括号):

double_factorial :: Integer->Integer
double_factorial n 
    | n<0 = error "negative number is given"
    | n==0 = 1
    | otherwise = factorial n * double_factorial (n-1)
    where
    factorial :: Integer->Integer
    factorial n 
        | n == 0  = 1
        | otherwise = n * factorial (n-1)
Run Code Online (Sandbox Code Playgroud)