2012-04-12 142 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