I am trying to convert a Haskell program to a Haskell GUI program, but since I am very very new at Haskell, every time I try something I get lots of errors. I asked on Stack Overflow many time for this program, but whenever an error disappears, two errors arise.
Sorry for asking similar question, but the program's ability what I intend to convert is very simple word searching. Receive input string, search the word, print on window.
Any advice, hint or example would be very helpful for me.
I am on Windows XP. Sorry for very poor code.
--GUI routine
import Graphics.UI.Gtk
import Text.Regex.Posix ((=~))
import Control.Monad (when)
--core routine
matchWord :: String -> String -> Int
matchWord file word = length . filter (== word) . concat $ file =~ "[^- \".,\n]+"
--main start
main :: IO ()
main =
do initGUI
win <- windowNew
windowSetTitle win "WORD SEARCHER"
win `onDestroy` mainQuit
fch <- fileChooserWidgetNew FileChooserActionOpen
containerAdd win fch
targetFile <- fileChooserGetFilena开发者_运维问答me fch --wrong?
ent <- entryNew
btn <- buttonNewWithLabel "Click to search"
st <- labelNew $ Just "Found : 0 "
col <- vBoxNew False 5
containerAdd col ent
containerAdd col btn
containerAdd col st
btn `onClicked` do targetWord <- entryGetText ent
fileData <- readFile Just targetFile
found <- matchWord fileData targetWord
labelSetText st found
containerAdd win col
widgetShowAll win
mainGUI
thank you for reading
This will get you started.
targetFile <- fileChooserGetFilename fch
At this point, targetFile
has type Maybe String
; that is, it will return either Just "somestring"
or Nothing
. You want the "somestring"
part, if it's available. You can get it by pattern matching:
Just targetFile <- fileChooserGetFilename fch
This will fail with an opaque error message if the result of fileChooserGetFilename
returned Nothing
. For more robustness you can case analyse the result:
maybeTargetFile <- fileChooserGetFilename fch
targetFile <- case maybeTargetFile of
Nothing -> fail "I need a filename!"
Just file -> return file
The other problem is in this line:
found <- matchWord fileData targetWord
x <- m
is used to bind the result of an action m
into the variable x
, but matchWord
returns an Int
, not an action (eg. IO a
for some a
).
精彩评论