I'm having a hard time finding out how to make something change every time the user interacts with my program. It's hard to explain so here's an example (Haskell + wxhaskell):
simulate :: Int -> Frame () -> IO ()
simulate qNr window = do
fdata <- readFile "qarchive"
case (split (listTake (split fdata '\n') qNr 0) '#') of
(qst:a:b:c:coralt:answer:x) -> do
-- GUI Controls Initialization (buttons,text,etc...)
nextButton <- button window [text := "Next Question ->", on command := set infoField [text := "Next Question"], position := pt 185 155]
return ()
main :: IO ()
main = start gui
gui :: IO ()
gui = do
window <- frame [text := "Question program", clientSize := sz 640 480]
headerText <- staticText window [text := "Title Text", fontSize := 20, position := pt 5 5]
simulate 0 window
return ()
I want some widgets to change when the "Next Question" button is pressed. I want to change these widgets to some values I read from a file. How can I keep track of what the current question number is? I cannot actually increment questionNumber as a variable, since Haskell doesn't permit such things. I guess there's another way to do it.
Example:
Initialize GUI
Read data from file
If button is pressed, increment question number by 1 and change widgets.
How do you tackle this kind of problem in a functional manner?
The arguments to functions are your variables. As the user enters new values, pass those values to functions.
For example, a simple program that updates a value based on user input:
main = loop 0
loop n = do
print n
v <- read `fmap` getLine
loop (n + v)
Note the recursive calls to 'loop' have a different value passed each time, based on what the user provided.
This is a fundamental way of thinking in functional programming -- what would be a local, mutable variable in a loop in an imperative program becomes a parameter to a recursive function in a functional program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With