2012-06-30 55 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