<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-15">
</head>
<body text="#000000" bgcolor="#ffffff">
Hi everyone,<br>
<br>
i'm trying to understand tail recursion, but im stuck when it comes
to tail recursion with tuples. Look at the following source code:<br>
<br>
module Main(main) where<br>
<br>
main = do<br>
putStrLn "tail recursion"<br>
print $ countOdd2 [0..10000000]<br>
<br>
{- Tail recursion doesnt work -}<br>
<br>
countOdd :: [Int] -> (Int, Int)<br>
countOdd lst = countOdd' lst (0,0)<br>
<br>
countOdd' :: [Int] -> (Int, Int) -> (Int, Int)<br>
countOdd' (x:xs) last = if odd x then<br>
countOdd' xs $! (fst last, snd
last + 1)<br>
else<br>
countOdd' xs $! (fst last + 1,
snd last)
<br>
countOdd' [] last = last<br>
<br>
{- Working tail recursion -}<br>
<br>
countOdd2 :: [Int] -> Int<br>
countOdd2 lst = countOdd2' lst 0<br>
<br>
countOdd2' :: [Int] -> Int -> Int <br>
countOdd2' (x:xs) last = if odd x then<br>
countOdd2' xs $! last + 1<br>
else<br>
countOdd2' xs last
<br>
countOdd2' [] last = last<br>
<br>
The tail recursion in the function <b>countOdd2 </b>works fine.
But it seems not to work in <b>countOdd </b>because i get a<b>
Stack space overflow </b>error. Can anyone rewrite <b>countOdd </b>so
that it works without a Stack space overflow?<br>
<br>
Thank you.<br>
<br>
Cheers<br>
Sebastian Arndt<br>
<br>
</body>
</html>