GHCi, version 7.4.2: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> let fac 0 = 1
Prelude> let fac n = product [1..n]
Prelude> fac 100000
Segmentation fault: 11
does anyone have any idea why this would be happening?
fac 10000
works
running on OS X 10.8.2
hmm, so loading from file:
fac :: Integer -> Integer
fac 0 = 1
fac n = product [1..n]
runs.
also interesting is that using
fac :: Int -> Int
returns 0
for fac 100000
. I would have expected (Just as JohnL) an error.
this site mentions:
is it something to do with the IO monad?
From a quick test, it appears to be caused by the fact that product
isn't strict, and the chain of thunks is causing the fault.
In the prelude, product
is defined as:
product = foldl (*) 1
If in ghci, you instead define it as:
> :m + Data.List
> let product = foldl' (*) 1
> let fac n = product [1..n]
Then it should work. I suspect when you specify the type signature, maybe some optimization is kicking in that isn't present otherwise... but haven't dug into it.
Btw, you don't need the let fac 0 = 1
line.
By giving it a type signature
fac :: Integer -> Integer
it will work. I do not fully understand why though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With