2011-05-02 83 views
4

我是一個Haskell noob總計,我希望有人能夠幫助我,因爲我已經在這裏呆了幾個小時,而且我只知道我正在做一些荒唐可笑的事情。無法與實際類型匹配的預期類型

程序應該掃描字典文件,以確定刪除空格的句子集合的所有有效單詞序列。

Ex。 「insidewaysoften」可以被分解爲「經常側向」,「內部方式軟化」等。

我在python中編寫了我的原型,它工作得很好(正如我的Java實現一樣),但是課程要求一個Haskell的實現,我不能得到它的工作。提前道歉的罪行我犯有危害的語言和GHC用下面的代碼:

import System.Environment 

main = do 
    [dictFilename,sentFilename] <- getArgs 
    dictFile <- readFile dictFilename 
    sentFile <- readFile sentFilename 

    mapM (\sentence -> solve "" "" sentence (words dictFile)) (words sentFile) 

solve prefix header [] dict = 
    if (header `elem` dict) 
    then return prefix ++ header 
    else return "" 

solve prefix header sent dict = do 
    let more = solve prefix (header ++ (take 1 sent)) (drop 1 sent) dict 

    if (header `elem` dict) 
    then return (solve (prefix ++ header ++ " ") "" sent dict) ++ more 
    else return more 
+0

那麼它有什麼問題?你會得到什麼錯誤?哪裏? – Gabe 2011-05-02 03:18:09

+0

你是否偶然採取與MeeksMan13相同的課程,他寫了[這個問題](http://stackoverflow.com/questions/5852841/splitting-a-sentence-without-any-whitespace-seperators-into-a-tencetence -with白色)?另外,是的,這是否會產生錯誤,還是隻是不正確?如果是這樣,它以什麼方式失敗? – 2011-05-02 03:25:35

+0

是的,傑弗裏,我看起來和MeeksMan13一樣。在我發佈我的信息後,我看到了他的問題。我發佈的代碼是返回類型錯誤,例如Rotsor在他的帖子中顯示的錯誤,我認爲根據他提供的信息我會很好。 – dpiers 2011-05-02 04:57:24

回答

9

當調查類錯誤就是寫下的功能類型的簽名,你知道的第一件事。

在此,解決可具有型

solve :: String -> String -> String -> [String] -> String 

solve :: String -> String -> String -> [String] -> IO String 

取決於它是否應該有任何副作用而計算的值。看到你在全國各地使用mapMreturn,我想IO版本可能已經打算。

現在,如果您記下簽名,您將開始獲得更有意義的錯誤消息。例如,而不是這樣的:

tmp.hs:19:16: 
    Couldn't match expected type `Char' with actual type `[Char]' 
    Expected type: [Char] 
     Actual type: [[Char]] 
    In the return type of a call of `solve' 
    In the first argument of `return', namely 
     `(solve (prefix ++ header ++ " ") "" sent dict)' 

,這並沒有太大的意義,你會得到這樣的:

tmp.hs:14:8: 
    Couldn't match expected type `IO String' with actual type `[a0]' 
    In the expression: return prefix ++ header 
    In the expression: 
     if (header `elem` dict) then return prefix ++ header else return "" 
    In an equation for `solve': 
     solve prefix header [] dict 
      = if (header `elem` dict) then 
        return prefix ++ header 
      else 
       return "" 

,這正好說明了問題的所在。函數應用程序在Haskell中的優先級最高,所以return prefix ++ header等於(return prefix) ++ header,這絕對不是你的意思。

順便說一句,如果我從返回類型中刪除IO,請刪除所有return s並通過添加putStrLn來更改調用,代碼將編譯並運行!唯一的問題是它將所有可能的句子連接成一個單獨的字符串而沒有任何分隔。

+0

謝謝!這正是我一直期待的答覆。 :) – dpiers 2011-05-02 04:59:31

相關問題