2011-06-11 60 views
0

我想将Haskell程序转换为Haskell GUI程序 但是由于我在Haskell非常新, 每当我尝试某些东西时,我都会遇到很多错误。 我在这个程序中多次询问堆栈溢出, 但每当错误消失时,就会出现两个错误。将TUI转换为haskell中的GUI

对不起,提问类似的问题,但 该程序的能力,我打算转换为 非常简单的单词搜索。 接收输入字符串,搜索单词,在窗口上打印。

任何建议,提示或示例将对我非常有用。

我在Windows XP上。对不起,代码很差。

--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 <- fileChooserGetFilename 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 

感谢您阅读

+0

什么是错误?它如何失败? – luqui 2011-06-11 09:07:51

回答

1

这将让你开始。

targetFile <- fileChooserGetFilename fch 

此时,targetFile的类型为Maybe String;也就是说,它将返回Just "somestring"Nothing。如果可用,您需要"somestring"部分。您可以通过模式匹配获得它:

Just targetFile <- fileChooserGetFilename fch 

这将失败,一个不透明的错误消息,如果fileChooserGetFilename结果返回Nothing。欲了解更多的鲁棒性可以区分分析结果:

maybeTargetFile <- fileChooserGetFilename fch 
targetFile <- case maybeTargetFile of 
        Nothing -> fail "I need a filename!" 
        Just file -> return file 

另一个问题是在这一行:

found <- matchWord fileData targetWord 

x <- m用于动作m的结果绑定到变量x,但matchWord返回一个Int,而不是一个动作(例如,IO a对于某些a)。