基本haskell程序,用于在文件中查找字符串
这是我第一次尝试Haskell,所以我的理解相当有限。我想写一个非常基本的程序来检查文件是否包含单词基本haskell程序,用于在文件中查找字符串,haskell,Haskell,这是我第一次尝试Haskell,所以我的理解相当有限。我想写一个非常基本的程序来检查文件是否包含单词ERROR。我提出了以下内容,当然这些内容甚至都没有编译 import Text.Regex.Posix containsErrorString :: String -> Bool containsErrorString x = x =~ "ERROR" :: Bool fileContainsErrorString fileName = do s <- readF
ERROR
。我提出了以下内容,当然这些内容甚至都没有编译
import Text.Regex.Posix
containsErrorString :: String -> Bool
containsErrorString x = x =~ "ERROR" :: Bool
fileContainsErrorString fileName = do
s <- readFile fileName
containsErrorString s
import Text.Regex.Posix
ContainesErrorString::String->Bool
ContainerErrorString x=x=~“错误”::Bool
FileContainesErrorString文件名=do
s轻微重写
我建议:
对于任何“严肃”的工作,请使用Text
而不是String
如果你不需要正则表达式,就不要使用正则表达式
代码:
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.
您的代码
你的方法没有任何问题。String
的使用仍然很常见,并且在大多数情况下完全可以接受。您的错误只是忘记了返回结果(您在monad中,IO
,而containersorstring
是一个纯函数)
而不是:
containsErrorString s
你应该有:
return (containsErrorString s)
轻松重写
我建议:
对于任何“严肃”的工作,请使用Text
而不是String
如果你不需要正则表达式,就不要使用正则表达式
代码:
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.
您的代码
你的方法没有任何问题。String
的使用仍然很常见,并且在大多数情况下完全可以接受。您的错误只是忘记了返回结果(您在monad中,IO
,而containersorstring
是一个纯函数)
而不是:
containsErrorString s
你应该有:
return (containsErrorString s)
主要问题是,filecontainersorstring::IO Bool
但是容器错误字符串(s::String)::Bool
因此,您需要将containersorstring
包装到IO
中,例如使用return::Monad m=>a->ma
fileContainsErrorString fileName = do
s <- readFile fileName
return $ containsErrorString s
filecontainersorstring fileName=do
主要的问题是,filecontainersorstring::IO Bool
但是容器错误字符串(s::String)::Bool
因此,您需要将containersorstring
包装到IO
中,例如使用return::Monad m=>a->ma
fileContainsErrorString fileName = do
s <- readFile fileName
return $ containsErrorString s
filecontainersorstring fileName=do
s