2011-11-02 32 views
2
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 

上面的代碼是給我:這是爲什麼給我「是約束剛性類型變量」錯誤

 
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 

這是爲什麼發生?

我被英寸

回答

5

length包裝我周圍的Haskell類型系統的寸頭返回Int;使用i = Data.List.genericLength wi = fromIntegral (length w)

+0

嗯,請詳述一下嗎?我認爲'Int'是'Num'的一個實例,爲什麼它仍然需要這種「fromIntegral」轉換? – nobody

+5

'heist'的類型承諾「你給我一個任意類型'n'和'Num n',我會給你一個類型爲[n] - > [n] - > n - > n'的函數」 。所以假設我們給了一些'n'(「剛性類型變量」),關於它我們什麼也不知道(除了它是'Num'的一個實例)。然後我們在'n = Int'處調用'func',它又返回一個'Int'。但是我們應該返回給定的'n'類型的值。 – FunctorSalad

+1

簡而言之,您的類型簽名承諾'heist'也適用於Double(以及其他)。但事實並非如此。 – Ingo

6

length總是返回Int。通過ifunc你應該說n應該是Int,但heist想要n是通用的,因此類型錯誤。

相關問題