Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem expressing a simple recursive function in Haskell

I decided to start learning Haskell and am having a little trouble with the syntax for expressing a simple recursive function to compute the factorial of the input argument.

myFac :: Integral a => a -> a
myFac 1 = 1
myFac x = x * myFac x-1

When I run it in ghci, it looks like the terminating condition is never invoked and I get a stack overflow. For the test cases below, I expected 1! = 1, 10! = 3628800, 2! = 2, 0.5! -> error condition, but instead got the following:

*Main> myFac 1
1
*Main> myFac 10
*** Exception: stack overflow
*Main> myFac 2
*** Exception: stack overflow
*Main> myFac 0.5

<interactive>:21:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘print’
  prevents the constraint ‘(Show a0)’ from being solved.
  Probable fix: use a type annotation to specify what ‘a0’ should be.
  These potential instances exist:
    instance Show HandlePosn -- Defined in ‘GHC.IO.Handle’
    instance Show BufferMode -- Defined in ‘GHC.IO.Handle.Types’
    instance Show Handle -- Defined in ‘GHC.IO.Handle.Types’
    ...plus 27 others
    ...plus 14 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
• In a stmt of an interactive GHCi command: print it

So, it seems to be treating the x argument as an integer since it doesn’t appreciate being given a float value, but then it should reach the terminating condition, but it doesn’t unless it starts there.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there some syntax I’m missing here? Is there someway to correct this so it works as I expected?

>Solution :

myFac x = x * myFac x-1

This line is being parenthesized as

myFac x = (x * (myFac x))-1

i.e. it’s calling myFac with the exact same argument it was given. Just add some extra parentheses and you’ll be just fine. Consider

myFac x = x * myFac (x - 1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading