【问题标题】:convert TUI to GUI in haskell在haskell中将TUI转换为GUI
【发布时间】:2011-06-11 07:00:32
【问题描述】:

我正在尝试将 Haskell 程序转换为 Haskell GUI 程序, 但由于我在 Haskell 非常新, 每次我尝试某些东西时,都会遇到很多错误。 我在 Stack Overflow 上多次询问过这个程序, 但只要一个错误消失,就会出现两个错误。

很抱歉问了类似的问题,但是 我打算转换的程序的能力是 非常简单的单词搜索。 接收输入字符串,搜索单词,在窗口打印。

任何建议、提示或示例都会对我很有帮助。

我使用的是 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

感谢您的阅读

【问题讨论】:

  • 错误是什么?它是如何失败的?

标签: user-interface haskell tui


【解决方案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 &lt;- m 用于将动作m 的结果绑定到变量x,但matchWord 返回一个Int,而不是一个动作(例如IO a 用于某些a) .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 2011-02-16
    • 2012-05-05
    • 1970-01-01
    相关资源
    最近更新 更多