2015-09-23 140 views
0

我寫Haskell代碼練習尾遞歸逆一個列表並想出了這個解決方案:爲什麼這個函數需要[[a]]?

reverseh' [] list = list 
reverseh' (x:xs) list = reverseh' (xs) (x ++ list) 
reverse' x = reverseh' x [] 

只與名單列表的作品,但我想它是有類型簽名[a] -> [a]

你能解釋我在做什麼錯嗎?

+0

我有同樣的問題,你的問題幫助我找到解決方案 –

回答

9

如果你沒有得到預期的類型,它是增加一個顯式類型簽名告訴你想要的類型是什麼編譯器,這裏是個好主意:

reverseh' :: [a] -> [a] -> [a] 

然後你得到一個編譯錯誤:

Couldn't match expected type `[a]' with actual type `a'  
    `a' is a rigid type variable bound by      
     the type signature for reverseh' :: [a] -> [a] -> [a] 
     at reverseh.hs:1:14         
Relevant bindings include         
    list :: [a] (bound at reverseh.hs:3:18)     
    xs :: [a] (bound at reverseh.hs:3:14)      
    x :: a (bound at reverseh.hs:3:12)       
    reverseh' :: [a] -> [a] -> [a] (bound at reverseh.hs:2:1) 
In the first argument of `(++)', namely `x'     
In the second argument of reverseh', namely `(x ++ list)' 

這告訴你,在(x ++ list)x需要以類型檢查是[a]類型,但類型簽名你心目中,x真的是型。所以你想用a -> [a] -> [a]類型的函數替換++,所以你用(x : list)去。

3

由於(x ++ list)在第二行表達,typechecker認爲x :: [a]。我想你想寫(x : list)

相關問題