hello I am very beginer of haskell
I am making GUI program that
-
open file selection dialog
-
take word
-
search the word in selected txt file
-
print number of found to label
but I stuck with error which I can’t solve it
I paste error and code here
could somebody please help me?
thank you
the full code is here
--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 <- buttonNew
st <- labelNew $ Just "Found : 0 "
col <- vBoxNew False 5
containerAdd col ent
containerAdd col btn
containerAdd col st
buttonSetLabel btn "Click to search"
btn `onClicked` do targetWord <- entryGetText ent
fileData <- readFile targetFile
found <- matchWord fileData targetWord
labelSetText st found
containerAdd win col
widgetShowAll win
mainGUI
the error is here
gui-word-search.hs:33:49:
Couldn't match expected type `FilePath'
against inferred type `Maybe FilePath'
In the first argument of `readFile', namely `targetFile'
In a 'do' expression: fileData <- readFile targetFile
fileChooserGetFilenamecan’t always return a filename (the user might click on “cancel” for example). For that reason its return type isMaybe FilePath, notFilePath. So if a file was chosen, it returns aJustcontaining theFilePath. If no file was chosen it returnsNothing.However
readFiletakes aFilePathas an argument, not aMaybe FilePath(callingreadFilewithNothingmakes no sense).So what you need to do is you need to pattern match on
targetFile. If it isNothing, you need to handle that somehow (you could print an error message, or just keep asking the user for a file until he picks one), and if it’s aJust, you take theFilePathit contains and feed that toreadFile.