Reputation: 15217
This is my first Haskell attempt so my understanding is fairly limited. I wanted to write a very basic program to check if a file contains the word ERROR
. I came up with the following which of course doesn't even compile.
import Text.Regex.Posix
containsErrorString :: String -> Bool
containsErrorString x = x =~ "ERROR" :: Bool
fileContainsErrorString fileName = do
s <- readFile fileName
containsErrorString s
Is this the right approach and if not what would be the correct way to accomplish this?
Thanks
Upvotes: 1
Views: 523
Reputation: 1803
Main problem is in fact that fileContainsErrorString :: IO Bool
,
but containsErrorString (s:: String) :: Bool
.
So, you need to wrap containsErrorString
into IO
, for example use return :: Monad m => a -> m a
fileContainsErrorString fileName = do
s <- readFile fileName
return $ containsErrorString s
Upvotes: 1
Reputation: 64740
A light rewrite
I suggest:
Text
instead of String
for any "serious" work.In code:
import Data.Text as T
containsErrorString :: Text -> Bool
containsErrorString = ("ERROR" `T.isInfixOf`)
fileContainsErrorString :: FilePath -> IO Bool
fileContainsErrorString = containsErrorString `fmap` T.readFile
-- Warning, code typed and not tested.
Your Code
There isn't anything wrong with your approach. The use of String
remains common and perfectly acceptable for most uses. Your error is just that you forgot to return
the result (you are in a monad, IO
, and containsErrorString
is a pure function).
Instead of:
containsErrorString s
you should have had:
return (containsErrorString s)
Upvotes: 5