0

I have created a GUI using gtk2hs and glade and then passed it to haskell code in the main::IO(). Then I have some coding for the windows say for labels, buttons and entry text. e.g.,

entry         <- xmlGetWidget xml castToEntry "entry1"
applyButton   <- xmlGetWidget xml castToButton "button1"

Then after clicking on the applybutton

onClicked applyButton $ do
number <- get entry entryText

Passed the value to a variable number

Then I wrote a function for squaring the number like this

sqr :: Int -> Int -> IO ()
sqr number = number * number

after the mainGUI.

Which doesn't work!!!!!!

It is supposed to be work as

I/p: Get a number from the user in GUI

o/p: Square of the number displayed in GUI

  • Sorry, where is the question? Also, sqr is not well-typed; do you mean `sqr :: Int -> Int -> Int`? – Joachim Breitner Aug 01 '12 at 08:46
  • @JoachimBreitner sorry I was not clear earlier. Hope it is clear now...Yes, I mean the same... – Thenraja Vettivelraj Aug 01 '12 at 09:10
  • Maybe [this IO tutorial](http://blog.sigfpe.com/2007/11/io-monad-for-people-who-simply-dont.html) or one of the many [monad](http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html) [tutorials](http://www.haskell.org/haskellwiki/All_about_monads) would be a good next step. – Daniel Wagner Aug 01 '12 at 09:19
  • So it seems you wanted `sqr number = print (number*number)`? That works, but it's better to separate the calculation from the I/O, `sqr :: Int -> Int -> Int; sqr x = x*x` and `print (sqr number)` when you want to print it. – Daniel Fischer Aug 01 '12 at 10:24

1 Answers1

1

Well, seems you're mixing IO and computational parts together.

You have a pure function to do the computation you need, like so:

sqr :: Int -> Int -> Int
sqr number = number * number

And you need to react on an event by issuing an IO action, namely, updating the state of the gui element. I assume you're trying to output the value into the same entry.

onClicked applyButton $ do
  num_str <- entryGetText entryText
  let number = read num_str
      squared = sqr number
  entrySetText entryText (show squared)

Please, take an attention, entryGetText/SetText work with strings, so you need to convert to and from Ints.

Dmitry Vyal
  • 2,347
  • 2
  • 24
  • 24
  • Thanks for the guidance. I have got a **Compilation error: Not in scope 'applyButton'** I have declared the applybutton, entrytext and other elements in IO. Then in the sqr function I have done the compuational part as you have mentioned – Thenraja Vettivelraj Aug 02 '12 at 06:59
  • It's hard to tell the reason without seeing the code (hint: use pastebin), but double check the identifer spelling, take in mind, Haskell is case-sensitive. Also, make sure that onClicked handler is below initial applyButton binding. – Dmitry Vyal Aug 03 '12 at 17:45
  • I checked my code and tried using pastebin. Still couldn't figure it out...Can I paste my code here? – Thenraja Vettivelraj Aug 08 '12 at 18:25