Search code examples
haskellncurses

How to do conditional on NCurses getEvent


I'm looking at the info from here: Hackage

I want different things to happen in my program depending on which arrow-key was pressed. Using the NCurses module, I can register an event with the getEvent function. But I cannot get my if statements to work on the stored event. This is my code:

main = runCurses $ do
    w <- defaultWindow
    e <- getEvent w (Just 300)
    let x = setX e

setX e
    | e == KeyLeftArrow = -1
    | e == KeyRightArrow = 1
    | otherwise = 0

This gives Couldn't match expected type ‘Key’ with actual type ‘Maybe Event’ So I change to e == Just Key...Arrow and then get

Couldn't match type ‘Event’ with ‘Key’
      Expected type: Maybe Key
        Actual type: Maybe Event

I guess this is because e is an Event, and I'm acting as if it were a Key, but even after trying this Key e == Just Key...Arrow it isn't working. How can I turn this event into a key? Or in some other way just be able to get my conditional on e to work?


Solution

  • Looking at getEvent definition

    getEvent
      :: Window  
      -> Maybe Integer  
      -> Curses (Maybe Event)
    

    you may notice that it returns Maybe Event wrapped into Curses monad. And in setX function you are trying to compare event to key. Compiler says you exactly about this mismatch:

    Couldn't match type ‘Event’ with ‘Key’
      Expected type: Maybe Key
        Actual type: Maybe Event
    

    Let's go to documentation and find a bit more about Event and Key types. Here is how Event is defined:

    data Event
        = EventCharacter Char
        | EventSpecialKey Key
        | EventMouse Integer MouseState
        | EventResized
        | EventUnknown Integer
    

    You may notice that Event has several variants (constructors) and one of them EventSpecialKey wraps Key. That is exactly what you need.

    setX e
        | e == Just (EventSpecialKey KeyLeftArrow) = -1
        | e == Just (EventSpecialKey KeyRightArrow) = 1
        | otherwise = 0