4

1..n からすべての階乗の積を計算する必要があります。この関数 double_factorial を (引数として少なくとも 2 または 3 を指定して) 呼び出すと、一瞬呼び出されたように見えますが、何も起こらず、数秒後に 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)
4

3 に答える 3

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)
于 2013-09-10T13:39:07.140 に答える