[英]Expanding the abbreviated words from a file in Haskell
我是使用Haskell中文件的新手,我编写了一个代码来检查.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"]
,但它不会t包含文件main.c
的单词。 我希望这足以使您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.