2013-02-15 79 views
0

我想實現Ha​​skell的標準字功能。我正在使用State Monad來解決問題。異常:模式匹配失敗Haskell

我的代碼是:

type WorS = ([String],String,String) 

words' :: State WorS [String] 
words' = do 
      (lwords, words, x:xs) <- get 
      case x:xs of 
      (' ':xs) -> (put (words:lwords, [], xs) >> words') 
      ([]) -> return lwords 
      (_:xs)-> (put (lwords, words ++ [x], xs) >> words') 

run_word' :: String ->[String] 
run_word' x = reverse $ fst (runState words' ([], [], x)) 

當我這樣做:

run_word' "guns and roses" 

我得到這個錯誤:

Exception: Pattern match failure in do expression 

的代碼加載在ghci中沒有任何錯誤。我究竟做錯了什麼?

+0

的[在功能上非詳盡模式(可能重複http://stackoverflow.com/questions/8435575/non -exhaustive-patterns-in-function) – 2013-02-15 20:54:39

回答

4
 (lwords,words,x:xs)<-get 

x:xs列表匹配與至少一個元素(x成爲第一個元素,xs成爲列表的其餘部分),所以你得到一個模式匹配失敗時,元組的第三個成員是[]

解決方法:更換

 (lwords,words,x:xs)<-get 
     case x:xs of 

 (lwords,words,xs)<-get 
     case xs of 

(並考慮後面的功能使用不同的變量名:它會混淆當你有相同名稱的兩個或多個變量。)

編輯:如果您打開警告(將-Wall標誌傳遞給ghc/ghci),您將g並在編譯時警告說,該模式可能無法在運行時匹配。 (您還可以得到一個關於有一個xs可變躲在另一個xs變量,稱爲陰影警告。)

+0

我沒有得到代碼中的錯誤。你能否詳細說明一下。 – 2013-02-15 19:44:57

+1

每次迭代循環時,狀態的第三個元素中的列表變短。當它變成空白列表時,你會發現模式匹配失敗。 – dave4420 2013-02-15 19:46:57

+0

謝謝。這解決了問題。 – 2013-02-15 20:20:49