[Haskell-cafe] Re: How to do this in FP way?
Achim Schneider
barsoap at web.de
Mon Jun 16 23:48:54 EDT 2008
"Magicloud" <magicloud.magiclouds at gmail.com> wrote:
> I think if I do not use a state, and the function would be called for
> many times, it would waste memory, if using something like loop,
> right?
>
nope, at least not in general.
update :: MyState -> Int -> MyState
draw :: MyState -> IO ()
mainLoop :: MyState -> Int -> IO ()
mainLoop st old = do
now <- getTimeOfDay
let td = now - old
st' = update st td
draw st'
mainLoop st' now
runs in constant space. Look up "tail recursion" in wikipedia.
> -----邮件原件-----
> 发件人: haskell-cafe-bounces at haskell.org
> [mailto:haskell-cafe-bounces at haskell.org] 代表 Achim Schneider
> 发送时间: 2008年6月16日 12:01
> 收件人: haskell-cafe at haskell.org
> 主题: [Haskell-cafe] Re: How to do this in FP way?
>
> "Magicloud Magiclouds" <magicloud.magiclouds at gmail.com> wrote:
>
> > static int old;
> > int diff (int now) { /* this would be called once a second */
> > int ret = now - old;
> > old = now;
> > return ret;
> > }
> >
> You do it with variables, of course. This is out of some GLUT code,
> using IORef's:
>
> idle :: State -> IdleCallback
> idle state = do
> t0 <- get $ t state
> t1 <- get elapsedTime
> t state $= t1
> let td = fromIntegral t1 - fromIntegral t0
> fps state $= 1/td * 1000
>
> angle' state $~! (+2)
>
> (bpx, bpy) <- get $ ballPos state
> (bvx, bvy) <- get $ ballVel state
>
> ballPos state $= (bpx + bvx*td, bpy + bvy*td)
> postRedisplay Nothing
>
> One half of all Haskell coders will tell you that mutable state isn't
> a good starting point to learn Haskell, the other half will tell you
> the same because they want to be cool kids, too.
>
--
(c) this sig last receiving data processing entity. Inspect headers for
past copyright information. All rights reserved. Unauthorised copying,
hiring, renting, public performance and/or broadcasting of this
signature prohibited.
More information about the Haskell-Cafe
mailing list