[Haskell-cafe] Re: OO Design in Haskell Example (Draft)

Tim Docker twd_gg at dockerz.net
Thu Mar 1 17:14:17 EST 2007


"Steve Downey" <sdowney at gmail.com> wrote:

> I'm not sure, though, what would happen if I tried to
> add state to the types. With the previous example,
> using existentials to create a reference type that
> holds elements of a type class that matches the interface,
> I think that it would be natural to hold state by having
> that element stored in a mutable state variable, and replacing
> the held values.

State is often best avoided, but if it's really what you want to do, you
can still capture a mutable variable in the closures captured inside the
record of functions.

Tim


import Data.IORef

data Component = Component {
    draw :: IO (),
    move :: (Int,Int) -> IO ()
}

newCircle :: IO Component
newCircle = do
    pref <- newIORef (0,0)
    return Component{draw=draw' pref, move=move' pref}
  where
    draw' pref = do
        p <- readIORef pref
        putStrLn ("circle at " ++ show p)

    move' pref p = writeIORef pref p









More information about the Haskell-Cafe mailing list