Eric Wong <wsysdu at gmail.com> wrote:
> I'm relatively new to haskell and due to my strong imperative
> background, it's really a pain to learn haskell. But I'm really
> indulged in it. :)
>> Now I think I understand the basics of Haskell very well, such as the
> type system and monad. And for those data-flow kind of applications, I
> can easily structure the problem in a functional way and sketch out an
> intuitive picture of the computation. But for simulation kind-of
> problems, in which I think OO really fits the best, what's the haskell
> way to structure such problems? I once thought maybe I can use the
> State monad to simulate objects. But it's really hard for me to
> implement, because I think State monad is used to simulate a global
> shared state, is it right?
>> Then what's the best way to simulate private states or just instead
> how to solve simulation problems such as a physical engine using the
> haskell way?
A state monad is used to encode a stateful computation. Whether its
state is global or not really only depends on how long the computation
lives. Here is how you can use one to maintain a list of objects:
computation :: State [Object] Result
computation = do
objs0 <- get
(result, objs1) <- doSomethingWith objs0
put objs1
return result
This is really just a convenient encoding of:
computation :: [Object] -> (Result, [Object])
Whether that [Object] state is global really only depends on where you
use evalState, execState or runState and how long the computation takes.
I often do something like this, which you can regard as global 'state'
(or rather a global environment):
type AppIO = ReaderT AppConfig IO
myApp :: AppIO ()
myApp = ...
main :: IO ()
main = getAppConfig >>= evalStateT myApp
Greets,
Ertugrul.
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://blog.ertes.de/