Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Haskell state

Name: Anonymous 2010-04-25 15:36

I've been learning Haskell for more than a month now and I did not have too much trouble understanding monads in general, but the state monad is giving me a headache. I think I have a vague idea how it works, but I am still unable to do the following:



data Point = Point {
    ptX :: Float,
    ptY :: Float }

main = do
    -- create window and register some event handlers
    mainGUI

onWndClick ev do
    let x = eventX ev
    let y = eventY ev
    -- put this point into list

onPaint canvas = do
    -- draw the points from the list


How the hell do I update a list of points in click event handler and draw those points in onPaint? My every attempt failed either with compiler errors or list not updating.

Name: Anonymous 2010-04-28 4:53

OP here, I just wanted to post the solution if anyone cares... What I needed was IORef monad, not State monad. State monad just "threads" state through computations, you need to pass it from one computation to next and then evaluate at the end, so it's unusable in GUI application with event handlers where you need global state. So, IORef is used like this:


main = do
    pointList <- newIORef []
    -- create window and register some event handlers, pass them pointList
    mainGUI

onWndClick pointList ev do
    let pt = Point (eventX ev) (eventY ev)
    modifyIORef pointList (\pts -> pts ++ [pt])

onPaint canvas pointList = do
    pts <- readIORef pointList
    -- draw the points from the list


I MENA HASKAL

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List