I'm trying to implement a main loop of sorts in Haskell, in C I would write it like this:
EntityInteraction *frame(Entity *eList, EntityInteraction *iList) {
parseInteractions(eList, iList);
return simulateEntities(eList);
}
int main() {
Entity eList[] = {...}
EntityInteraction *iList = NULL;
while(true) {
iList = frame(eList, iList);
}
}
So I attempted to replicate this in haskell by making frame a recursive function:
frame :: [Entity] -> [EntityInteraction] -> IO ()
frame eList iList = do
frame (parseInteractions iList eList) (simulateEntities eList)
main :: IO ()
main = do
let entList = [...]
frame entList []
But this just results in a stack overflow as expected, so my question is what is the propper way to do a main loop in haskell that uses mutable state?
(I've been programming in C as a hobby for 4 years and I'm just starting to learn haskell)
elist
orilist
just grows too big at some point? Also, how did you compile your program? Try withghc -O2
just to make sure. – Mike Hartl Aug 9 '13 at 6:29main = frame
;frame = return () >> frame
, and while this obviously burns the cpu, it happily runs forever in constant space (using 800k memory). – Mike Hartl Aug 9 '13 at 6:51print
before the recursive call toframe
, and you'll see that it's doing just fine. (Laziness does change the nature of "mutable" state -- i.e. you are building up thunks rather than computing anything -- but you are on the right track, and observing the results will help) – luqui Aug 9 '13 at 7:34