2012-06-30 51 views
6

您好以下代码是一个wordfeud程序。它允许您搜索匹配前缀,后缀和一些字母的单词列表。我的问题是,我不想使用底部的列表,而是使用包含单词的外部文本文件并将其加载到列表中。我如何去做这件事?Haskell将外部txt文件加载到列表中

count :: String -> String -> Int 
count _[] = 0 
count [] _ = 0 
count (x:xs) square 
    |x `elem` square = 1 + count xs (delete x square) 
    |otherwise = count xs square 

check :: String -> String -> String -> String -> Bool 
check prefix suffix word square 
    | (length strippedWord) == (count strippedWord square) = True 
    | otherwise = False 
    where 
     strippedWord = drop (length prefix) (take ((length word) - (length suffix)) word) 


wordfeud :: String -> String -> String -> [String] 
wordfeud a b c = test1 
    where 
    test =["horse","chair","chairman","bag","house","mouse","dirt","sport"] 

    test1 = [x| x <- test, a `isPrefixOf` x, b `isSuffixOf` x, check a b x c] 
+0

有关您的代码的两个简短提示:1.在Haskell函数应用程序中优先于中缀运算符。也就是说,像'length strippedWord == count strippedWord square'这样的表达式相当于'(length strippedWord)==(count strippedWord square)'。 2.在函数check中,函数的结果是相等性检查的值。因此,您可以通过相等性检查来替换警卫(带有竖条的部分)。 –

+0

你的意思是我可以用这条线代替卫兵“长度strippedWord ==计数strippedWord square = True”? – tutu

+1

不好意思,我的意思是你可以使用'check prefix suffix word square = length strippedWord == count strippedWord square'。也就是说,'check'的应用程序的结果是应用'=='的结果。 –

回答

5

很简单,用lines功能的帮助(或words,当单词被空格的其他一些形式大于换行分隔):

-- Loads words from a text file into a list. 
getWords :: FilePath -> IO [String] 
getWords path = do contents <- readFile path 
        return (lines contents) 

此外,你可能不得不如果你还没有这样做,请阅读Haskell中的IO(我推荐使用Google的'io haskell教程')。您还需要它将交互性引入到您的程序中。

+0

'words'对于任何空白都是有用的,'lines'基本上是一种分割参数较窄的单词形式。例如:“单词”嗨\ n \ n \ n \ n \ n \ n“” - > [“您好”,“如何”,“是”,“您”]''。 –

+0

你是对的。我会让答案更具体。 – AardvarkSoup

+0

@AardvarkSoup我无法得到这个工作。我只是用我的文本文件''dictionary.txt''的名称来替换'path'?另外,我在哪里放置这段代码,在'where'和'checkw = [x |之间x < - 测试'? – tutu