Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell segmentation fault 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

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:

  • More specifically, SegmentationFault is a way a type-unsafe language spells DoesNotUnderstand. In a typesafe statically-typed language like Haskell, you shouldn't see segfaults.

is it something to do with the IO monad?

like image 327
beoliver Avatar asked Jan 20 '13 01:01

beoliver


2 Answers

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.

like image 183
Steve Avatar answered Oct 14 '22 23:10

Steve


By giving it a type signature

fac :: Integer -> Integer

it will work. I do not fully understand why though.

like image 20
beoliver Avatar answered Oct 14 '22 23:10

beoliver