Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional Programming, recursing a game state loop

I was planning on writing a simple game to test out my understanding of functional programming. The functional way of doing the main loop, would be recursing it, but won't this eat up memory as more and more stack frames are generated?

Thanks

An example from How can you do anything useful without mutable state?

// imperative version
pacman = new pacman(0, 0)
while true
    if key = UP then pacman.y++
    elif key = DOWN then pacman.y--
    elif key = LEFT then pacman.x--
    elif key = UP then pacman.x++
    render(pacman)

// functional version
let rec loop pacman =
    render(pacman)
    let x, y = switch(key)
        case LEFT: pacman.x - 1, pacman.y
        case RIGHT: pacman.x + 1, pacman.y
        case UP: pacman.x, pacman.y - 1
        case DOWN: pacman.x, pacman.y + 1
    loop(new pacman(x, y))
like image 349
Peter Avatar asked Dec 14 '25 05:12

Peter


1 Answers

You have implemented your loop function using tail recursion, i.e. the recursive call to loop is the last thing in the function. This allows the compiler/interpreter (depending on the language) to pop the current stack frame immediately and replace it with the recursive call's frame.

Long story short, the way you have implemented it, there will be no stack overflow, and loop can run for as long as needed.

like image 190
waldrumpus Avatar answered Dec 15 '25 18:12

waldrumpus