【发布时间】:2012-08-17 17:11:08
【问题描述】:
我打算写一个简单的游戏来测试我对函数式编程的理解。执行主循环的功能方式是递归它,但这不会随着越来越多的堆栈帧生成而消耗内存吗?
谢谢
来自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))
【问题讨论】:
-
你使用什么功能语言?
-
Clojure,但如果它取决于语言,我也会热衷于了解 F#。
标签: recursion functional-programming