[Haskell-beginners] folds again -- myCycle
7stud
bbxx789_05ss at yahoo.com
Sat Mar 14 03:57:57 EDT 2009
I spent a long time working on a solution for an exercise in RWH: if you can,
use foldr to mimic haskell's cycle function. At first, I wondered whether
it was even possible. Then I worked on some ideas, and finally I came up with
a solution. Surprisingly, my solution ended up being very simple:
myCycle [] = []
myCycle xs = helperFunc xs [1..]
where helperFunc ys foldrXs = foldr accFunc [] foldrXs
where accFunc _ acc = ys ++ acc
I tested it out, and it worked like a charm:
*Main> let x = myCycle [1, 2, 3]
*Main> take 2 x
[1,2]
*Main> take 10 x
[1,2,3,1,2,3,1,2,3,1]
*Main> take 30 x
[1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3]
After re-examining my solution, I decided that this line:
--where accFunc _ acc = ys ++ acc
read better like this:
--where accFunc _ acc = acc ++ ys
The altered function returns a list just fine. But when I use take on the
list, I get a stack overflow. What is being thunked in both cases?
Thanks.
More information about the Beginners
mailing list