为什么这给了我"是一个严格的类型变量绑定"错误

nob*_*ody 2 haskell types

heist :: (Num n) => [n] -> [n] -> n -> n
-- heist [] [] _ = 0
heist w v maxw = func w v i j where
    i = length w
    j = maxw  
func :: (Num n) => [n] -> [n] -> n -> n -> n 
func _ _ 0 0 = 0
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我:

Heist.hs:15:27:
    Could not deduce (n ~ Int)
    from the context (Num n)
      bound by the type signature for
                 heist :: Num n => [n] -> [n] -> n -> n
      at Heist.hs:(15,1)-(17,16)
      `n' is a rigid type variable bound by
          the type signature for heist :: Num n => [n] -> [n] -> n -> n
          at Heist.hs:15:1
    In the third argument of `func', namely `i'
    In the expression: func w v i j
    In an equation for `heist':
        heist w v maxw
          = func w v i j
          where
              i = length w
              j = maxw

为什么会这样?

我一寸一寸地绕着Haskell型系统缠绕我的脑袋

Sjo*_*her 7

length总是会回来的Int.通过传递ifunc你说n应该是Int,但heist希望n是通用的,因此类型错误.


Fun*_*lad 5

length返回Int; 用i = Data.List.genericLength wi = fromIntegral (length w).

  • 'heist`的类型承诺"你给我一个带有'Num n`的任意类型`n`,我会给你一个类型为`[n] - > [n] - > n - > n`"的函数.所以假设我们给了一些类型`n`("刚性类型变量"),我们什么都不知道(除了它是`Num`的一个实例).然后我们在`n = Int`处调用`func`,它再次返回一个`Int`.但是我们应该返回我们给出的"n"类型的值. (5认同)
  • 简而言之,您的类型签名承诺 `heist` 也适用于 Double(以及其他)。但事实并非如此。 (2认同)