Haskell segmentation error with factorial

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 

Can anyone understand why this is happening?

fac 10000 works

works on OS X 10.8.2

hmm, so loading from a file:

 fac :: Integer -> Integer fac 0 = 1 fac n = product [1..n] 

works.

also interesting that using

fac :: Int -> Int

returns 0 for fac 100000 . I would expect (like JohnL) an error.

this site mentions:

  • More specifically, SegmentationFault is the way that an insecure fuzzy language calls DoNotUnderstand. In a typed statically typed language like Haskell, you should not see segfaults.

Does this have anything to do with the IO monad?

+6
source share
2 answers

From a quick test, this is apparently due to the fact that the product not strict, and the thunks chain causes an error.

In the prelude, product is defined as:

 product = foldl (*) 1 

If in ghci you define it as:

 > :m + Data.List > let product = foldl' (*) 1 > let fac n = product [1..n] 

Then it should work. I suspect that when you specify the type signature, maybe some kind of optimization starts, which is not otherwise ... but did not stick into it.

Btw, you do not need the string let fac 0 = 1 .

+2
source

Giving him a signature like

fac :: Integer -> Integer

he will work. However, I do not quite understand why.

+1
source

All Articles