Haskell program crash - infinite recursion? wrong, where is the expression?

I need to calculate the product of all factorials from 1..n. When I call this double_factorial function (with at least 2 or 3 as args), it seems to be called for a moment, but nothing happens, and after a few seconds GHCi just closes. What's wrong? Is there some kind of infinite recursion that I don't see? Here is my code:

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
source share
3 answers

(double_factorial n-1) means ((double_factorial n) - 1) , so yes, this is a problem with infinite recursion.

+11
source

Firstly, since you opened GHCi directly, the terminal window in which it works closes as soon as GHCi stops working. If you open cmd (or a similar terminal) and then use GHCi, you will see the error that GHCi throws when it stops working. In this case we get:

 <interactive>: out of memory 

This suggests a problem with infinite recursion, as you already suspected.

Since factorial is a simpler function, it is easier to check if its recursive call is the culprit. This means that factorial n - 1 means (factorial n) - 1 , not factorial (n - 1) . And calling factorial n in the definition of factorial n is pretty much the case of an infinite recursion tutorial. In double_factorial we see the same problem.

+6
source

You have a recursion problem: fx - 1 does not match f (x - 1) . Solution (removing unnecessary brackets and adding the necessary ones):

 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) 
+5
source

Source: https://habr.com/ru/post/1501477/


All Articles