On Thu, Apr 23, 2009 at 7:02 AM, Mozhgan Kabiri <mozhgan_...@hotmail.com>wrote:
> Hi Luck , > > I got you email from the Haskell Cafe list. Hope you don't mind. > Recently I was running a simple program in Haskell and keep getting *** > Exception: stack overflow error ! > > I don't know how to solve it or handle it ! I tried to find the same > problem on the web in order to get some guide but it wasn't successful.Hope > you can give me some clue. > In the future, why don't you ask this kind of question on haskell-cafe or haskell-beginners? > > > Here is the code : > > import Control.Monad > import Text.Printf > > sumit :: Int -> Int > sumit n = sumCal 0 n 0 where > sumCal i n sum | i < n = sumCal (i+1) n (sum+i) > | otherwise = sum > This is probably your problem. If you do tail recursion, it needs to be strict. If you don't strictly tail recurse, you end up returning a massive thunk (i.e. a lazy expression like 0+1+2+3+4+5+6+7+8+9+10+11+12+...) which needs to be evaluated all in one go, which will overflow your stack. It is a little tricky, I know... sumCal i n sum | i < n = sumCal (i+1) n $! sum+i | otherwise = sum However, there is a function "sum" in the prelude, so you can do this much more simply: sumit :: Int -> Int sumit n = sum [1..n] :-) Luke > > loopOut :: Int -> IO() > loopOut n | n <= 1000000 > = do > loopIn 0 (1000000000*n) n 0 > loopOut (n*10) > | otherwise = printf "Done!" > > > loopIn :: Int -> Int -> Int -> Int -> IO() > loopIn i ub n sum | i < ub > = do > loopIn (i+1) ub n (sumit n) > printf "n=%10d sum=%15d" n sum > | otherwise = printf "\n" > > main :: IO () > main > =do > printf "Started .." > loopOut 1000 > > Actually the next step it to parallelize the code with STM.But even at this > stage it doesn't work ! So, if you can help me with this,I'd be grateful. > > Thanks, > Mozhgan > > ------------------------------ > " Upgrade to Internet Explorer 8 Optimised for MSN. " Download > Now<http://extras.uk.msn.com/internet-explorer-8/?ocid=T010MSN07A0716U> >
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe