我是处理哈斯克尔文件的新手。我编写了一个代码来检查.c
文件中单词的出现。单词列在.txt
文件中。
例如:
abbreviations.txt
ix=index
ctr=counter
tbl=table
另一个文件是:
main.c
main ()
{
ix = 1
for (ctr =1; ctr < 10; ctr++)
{
tbl[ctr] = ix
}
}
遇到ix
时,应该将其扩展到index
,并且对于ctr
和tbl
也是如此。
这是我写的代码来检查出现次数(尚未替换遇到的单词(
import System.Environment
import System.IO
import Data.Char
import Control.Monad
import Data.Set
main = do
s <- getLine
f <- readFile "abbreviations.txt"
g <- readFile s
let dict = fromList (lines f)
mapM_ (spell dict) (words g)
spell d w = when (w `member` d) (putStrLn w)
在执行代码时,它不会给出任何输出。
我尝试使用hgetLine
而不是上面的代码读取文件,然后使用words
将其转换为单词列表
getLines' h = do
isEOF <- hIsEOF h
if isEOF then
return ()
else
do
line <- hGetLine h
list<-remove (return (words line))
getLines' h
-- print list
main = do
inH <- openFile "abbreviations.txt" ReadMode
getLines' inH
hClose inH
remove [] = []
remove (x:xs)| x == "=" = remove xs
| otherwise = x:remove (xs)
但它给了我与IO((相关的错误,还有其他方法可以执行以下操作吗?
我哪里出错了?
感谢您的任何帮助。
首先,您的拼写函数有问题。它还应该有一个 else 子句:
spell :: (Show a, Ord a) => Set a -> a -> IO ()
spell d w = if (w `member` d)
then print d
else return ()
另外,请注意,我已将您的putStrLn
更改为print
,并在您的代码中添加了一个类型签名。
在执行代码时,它不会给出任何输出。
这是因为,它总是转到spell
函数中的 else 子句。如果您尝试跟踪程序的执行,那么您会注意到,您的dict
变量实际上将包含以下 Set: ["ctr=counter","ix=index","tbl=table"]
,并且它不包含文件main.c
的单词。我希望这足以让你开始。