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.
Is there some syntax I'm missing here? Is there someway to correct this so it works as I expected?