2012-04-12 146 views
0

我一直在這段代碼中運行了將近2個小時,並且不斷收到相同的編譯器錯誤消息。我已經完成了我的研究,但找不到答案Haskell中類型聲明中的列表列表

buildTable :: Int -> Int -> (Int -> Int -> a) -> [[a]] 

buildTable n m fun = [[ fun x y 
        | x <- [0..n-1]] 
        | y <- [0..m-1]] 


lookupAns :: Int -> Int -> [[Int]] -> Int 
lookupAns len1 len2 theArray = 
    theArray !! len1 !! len2 


lcsLength :: String -> String -> Int 
lcsLength s1 s2 = 
    let 
    n1 = (length s1) 
    n2 = (length s2) 
    table = buildTable (n1 n2 lcsHelp) 

    lcsHelp = if (n1 == 0 || n2 == 0) 
       then 0 

       else if (last s1 == last s2) 

       then      
        (lookupAns 
         (n1 - 1) 
         n2 
         table) 
         + 1 
       else 
        max 
         (lookupAns 
          n1 
          (n2-1) 
          table) 
         (lookupAns 
          (n1-1) 
          n2 
          table) 





    in lookupAns 
     (length s1) 
     (length s2) 
     table 

現在無論我嘗試什麼,我都會得到相同的錯誤消息。錯誤消息是「無法匹配期望的類型」[[Int]] - > Int',其實際類型爲[Int]「其他規範指向代碼末尾的第一個max調用。請幫忙,這真的令人沮喪

它現在編譯並運行我的新代碼。我會確保稍後發佈它,因爲它遲到了,我會把它放下來過夜。

+0

注意名單對於這種類型的東西並不是很好,因爲它們在空間方面有很大的開銷,而且_O(n)_索引很慢。對於小案例或原型,它們都可以,但對於任何嚴重的問題,您應該使用數組或矢量來代替。 – hammar 2012-04-12 04:29:26

回答

1

lcslength中的第一個lookupAns應用於太少的參數。

+0

這是一個錯字 – user1327964 2012-04-12 02:16:26

4

這是錯誤的:

table = buildTable (n1 n2 lcsHelp) 

buildTable具有類型。 buildTable (n1 n2 lcsHelp)將其應用於一個參數,即(n1 n2 lcsHelp)。所以table將有類型Int -> (Int -> Int -> a) -> [[a]],作爲lookupAns的第三個參數傳遞無效。

不知道(n1 n2 lcsHelp)試圖將一個整數n1應用於兩件事情,這是顯而易見的垃圾。

雖然我沒有收到您引用的錯誤消息。 GHCI給我:

Loading package ghc-prim ... linking ... done. 
Loading package integer-gmp ... linking ... done. 
Loading package base ... linking ... done. 
[1 of 1] Compiling Main    (bar.hs, interpreted) 

bar.hs:18:13: 
    Couldn't match expected type `[[Int]]' 
       with actual type `Int -> (Int -> Int -> a0) -> [[a0]]' 
    In the return type of a call of `buildTable' 
    In the expression: buildTable (n1 n2 lcsHelp) 
    In an equation for `table': table = buildTable (n1 n2 lcsHelp) 

我不知道這是否是因爲你已經發布的代碼實際上不是你編譯得到你的錯誤信息(這是通過這樣的事實,你必須暗示的代碼糾正拼寫錯誤),或者只是GHCi在與您正在使用的編譯器不同的地方拾取不一致。

我猜你可能是指:

table = buildTable n1 n2 lcsHelp 

但是,這再次給了我一個不同的錯誤。

0

我將代碼粘貼在hpaste上,以便更容易找出問題。正如@Ben已經指出的那樣,問題是table的類型。

buildTable函數的類型爲。你稱它爲table = buildTable (n1 n2 lcsHelp)。所以,table的類型將是Int -> (Int -> Int -> a) -> [[a]]。這種類型的無效傳遞到lookupAns函數的類型是Int -> Int -> [[Int]] -> Int

如果你是做這樣的事情table = buildTable n1 n2 lcsHelp,我相信可能是你的意圖,然後buildTable類型簽名必須改變,因爲你會遇到這種錯誤

Couldn't match expected type `Int -> Int -> Int' 
      with actual type `Int' 
In the third argument of `buildTable', namely `lcsHelp' 

這是因爲現在的lcsHelp函數返回一個Int(因爲從if..else語句返回值)不符合實際的類型buildTable功能。

所以,如果你可以更多地解釋你想要達到的目標,那麼將會更容易幫助你。最有可能的是lcsHelp函數的類型是你需要重新訪問的。可能是buildTable函數不需要以函數作爲輸入參數。

0

意見夫婦 1. lcsHelp採用無參數 2. lookupAns其他-IF-THEN採取錯誤的論點,缺少table

我有一點點修改爲:http://hpaste.org/66862